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

#include <stddef.h>

#include "common.h"
11
#include "repository.h"
12
#include "index.h"
13
#include "tree.h"
14
#include "tree-cache.h"
15
#include "hash.h"
16 17
#include "iterator.h"
#include "pathspec.h"
18
#include "ignore.h"
19
#include "blob.h"
20

21
#include "git2/odb.h"
22
#include "git2/oid.h"
23
#include "git2/blob.h"
24
#include "git2/config.h"
25
#include "git2/sys/index.h"
26 27 28 29 30 31 32 33 34 35 36

#define entry_size(type,len) ((offsetof(type, path) + (len) + 8) & ~7)
#define short_entry_size(len) entry_size(struct entry_short, len)
#define long_entry_size(len) entry_size(struct entry_long, len)

#define minimal_entry_size (offsetof(struct entry_short, path))

static const size_t INDEX_FOOTER_SIZE = GIT_OID_RAWSZ;
static const size_t INDEX_HEADER_SIZE = 12;

static const unsigned int INDEX_VERSION_NUMBER = 2;
37 38 39 40
static const unsigned int INDEX_VERSION_NUMBER_EXT = 3;

static const unsigned int INDEX_HEADER_SIG = 0x44495243;
static const char INDEX_EXT_TREECACHE_SIG[] = {'T', 'R', 'E', 'E'};
41
static const char INDEX_EXT_UNMERGED_SIG[] = {'R', 'E', 'U', 'C'};
Edward Thomson committed
42
static const char INDEX_EXT_CONFLICT_NAME_SIG[] = {'N', 'A', 'M', 'E'};
43

44 45
#define INDEX_OWNER(idx) ((git_repository *)(GIT_REFCOUNT_OWNER(idx)))

46 47 48 49 50 51 52 53 54 55 56
struct index_header {
	uint32_t signature;
	uint32_t version;
	uint32_t entry_count;
};

struct index_extension {
	char signature[4];
	uint32_t extension_size;
};

57 58 59 60 61
struct entry_time {
	uint32_t seconds;
	uint32_t nanoseconds;
};

62
struct entry_short {
63 64
	struct entry_time ctime;
	struct entry_time mtime;
65 66 67 68 69 70 71 72
	uint32_t dev;
	uint32_t ino;
	uint32_t mode;
	uint32_t uid;
	uint32_t gid;
	uint32_t file_size;
	git_oid oid;
	uint16_t flags;
schu committed
73
	char path[1]; /* arbitrary length */
74 75 76
};

struct entry_long {
77 78
	struct entry_time ctime;
	struct entry_time mtime;
79 80 81 82 83 84 85 86 87
	uint32_t dev;
	uint32_t ino;
	uint32_t mode;
	uint32_t uid;
	uint32_t gid;
	uint32_t file_size;
	git_oid oid;
	uint16_t flags;
	uint16_t flags_extended;
schu committed
88
	char path[1]; /* arbitrary length */
89 90
};

Edward Thomson committed
91 92
struct entry_srch_key {
	const char *path;
93
	size_t pathlen;
Edward Thomson committed
94 95 96
	int stage;
};

97 98 99 100 101 102 103 104 105 106 107 108
struct entry_internal {
	git_index_entry entry;
	size_t pathlen;
	char path[GIT_FLEX_ARRAY];
};

struct reuc_entry_internal {
	git_index_reuc_entry entry;
	size_t pathlen;
	char path[GIT_FLEX_ARRAY];
};

109 110 111 112
/* local declarations */
static size_t read_extension(git_index *index, const char *buffer, size_t buffer_size);
static int read_header(struct index_header *dest, const void *buffer);

113
static int parse_index(git_index *index, const char *buffer, size_t buffer_size);
114
static bool is_index_extended(git_index *index);
115
static int write_index(git_index *index, git_filebuf *file);
116

117
static void index_entry_free(git_index_entry *entry);
Edward Thomson committed
118 119
static void index_entry_reuc_free(git_index_reuc_entry *reuc);

120
int git_index_entry_srch(const void *key, const void *array_member)
121
{
Edward Thomson committed
122
	const struct entry_srch_key *srch_key = key;
123
	const struct entry_internal *entry = array_member;
124 125
	int cmp;
	size_t len1, len2, len;
126

127 128
	len1 = srch_key->pathlen;
	len2 = entry->pathlen;
129
	len = len1 < len2 ? len1 : len2;
Edward Thomson committed
130

131 132 133 134 135 136 137
	cmp = memcmp(srch_key->path, entry->path, len);
	if (cmp)
		return cmp;
	if (len1 < len2)
		return -1;
	if (len1 > len2)
		return 1;
Edward Thomson committed
138

139
	if (srch_key->stage != GIT_INDEX_STAGE_ANY)
140
		return srch_key->stage - GIT_IDXENTRY_STAGE(&entry->entry);
141 142

	return 0;
143 144
}

145
int git_index_entry_isrch(const void *key, const void *array_member)
146
{
Edward Thomson committed
147
	const struct entry_srch_key *srch_key = key;
148
	const struct entry_internal *entry = array_member;
149 150
	int cmp;
	size_t len1, len2, len;
Edward Thomson committed
151

152 153
	len1 = srch_key->pathlen;
	len2 = entry->pathlen;
154
	len = len1 < len2 ? len1 : len2;
Edward Thomson committed
155

156
	cmp = strncasecmp(srch_key->path, entry->path, len);
Edward Thomson committed
157

158 159 160 161 162 163 164 165
	if (cmp)
		return cmp;
	if (len1 < len2)
		return -1;
	if (len1 > len2)
		return 1;

	if (srch_key->stage != GIT_INDEX_STAGE_ANY)
166
		return srch_key->stage - GIT_IDXENTRY_STAGE(&entry->entry);
167 168

	return 0;
Edward Thomson committed
169 170
}

171
static int index_entry_srch_path(const void *path, const void *array_member)
Edward Thomson committed
172
{
173 174
	const git_index_entry *entry = array_member;

Edward Thomson committed
175 176 177
	return strcmp((const char *)path, entry->path);
}

178
static int index_entry_isrch_path(const void *path, const void *array_member)
Edward Thomson committed
179 180 181 182
{
	const git_index_entry *entry = array_member;

	return strcasecmp((const char *)path, entry->path);
183 184
}

185
int git_index_entry_cmp(const void *a, const void *b)
186
{
Edward Thomson committed
187
	int diff;
188 189
	const git_index_entry *entry_a = a;
	const git_index_entry *entry_b = b;
190

Edward Thomson committed
191 192 193
	diff = strcmp(entry_a->path, entry_b->path);

	if (diff == 0)
194
		diff = (GIT_IDXENTRY_STAGE(entry_a) - GIT_IDXENTRY_STAGE(entry_b));
Edward Thomson committed
195 196

	return diff;
197 198
}

199
int git_index_entry_icmp(const void *a, const void *b)
200
{
Edward Thomson committed
201
	int diff;
202 203 204
	const git_index_entry *entry_a = a;
	const git_index_entry *entry_b = b;

Edward Thomson committed
205 206 207
	diff = strcasecmp(entry_a->path, entry_b->path);

	if (diff == 0)
208
		diff = (GIT_IDXENTRY_STAGE(entry_a) - GIT_IDXENTRY_STAGE(entry_b));
Edward Thomson committed
209 210 211 212

	return diff;
}

Edward Thomson committed
213 214 215 216
static int conflict_name_cmp(const void *a, const void *b)
{
	const git_index_name_entry *name_a = a;
	const git_index_name_entry *name_b = b;
217

Edward Thomson committed
218 219
	if (name_a->ancestor && !name_b->ancestor)
		return 1;
220

Edward Thomson committed
221 222
	if (!name_a->ancestor && name_b->ancestor)
		return -1;
223

Edward Thomson committed
224 225
	if (name_a->ancestor)
		return strcmp(name_a->ancestor, name_b->ancestor);
226

Edward Thomson committed
227 228
	if (!name_a->ours || !name_b->ours)
		return 0;
229

Edward Thomson committed
230 231 232
	return strcmp(name_a->ours, name_b->ours);
}

Vicent Marti committed
233 234 235
/**
 * TODO: enable this when resolving case insensitive conflicts
 */
236
#if 0
Edward Thomson committed
237 238 239 240
static int conflict_name_icmp(const void *a, const void *b)
{
	const git_index_name_entry *name_a = a;
	const git_index_name_entry *name_b = b;
241

Edward Thomson committed
242 243
	if (name_a->ancestor && !name_b->ancestor)
		return 1;
244

Edward Thomson committed
245 246
	if (!name_a->ancestor && name_b->ancestor)
		return -1;
247

Edward Thomson committed
248 249
	if (name_a->ancestor)
		return strcasecmp(name_a->ancestor, name_b->ancestor);
250

Edward Thomson committed
251 252
	if (!name_a->ours || !name_b->ours)
		return 0;
253

Edward Thomson committed
254 255
	return strcasecmp(name_a->ours, name_b->ours);
}
256
#endif
Edward Thomson committed
257

Edward Thomson committed
258 259 260 261 262
static int reuc_srch(const void *key, const void *array_member)
{
	const git_index_reuc_entry *reuc = array_member;

	return strcmp(key, reuc->path);
263 264
}

Edward Thomson committed
265
static int reuc_isrch(const void *key, const void *array_member)
266
{
Edward Thomson committed
267
	const git_index_reuc_entry *reuc = array_member;
268

Edward Thomson committed
269
	return strcasecmp(key, reuc->path);
270 271
}

Edward Thomson committed
272
static int reuc_cmp(const void *a, const void *b)
273
{
Edward Thomson committed
274 275
	const git_index_reuc_entry *info_a = a;
	const git_index_reuc_entry *info_b = b;
276 277 278

	return strcmp(info_a->path, info_b->path);
}
279

Edward Thomson committed
280 281 282 283 284 285 286 287
static int reuc_icmp(const void *a, const void *b)
{
	const git_index_reuc_entry *info_a = a;
	const git_index_reuc_entry *info_b = b;

	return strcasecmp(info_a->path, info_b->path);
}

288 289 290 291 292 293 294
static void index_entry_reuc_free(git_index_reuc_entry *reuc)
{
	git__free(reuc);
}

static void index_entry_free(git_index_entry *entry)
{
295 296 297
	if (!entry)
		return;

298
	memset(&entry->id, 0, sizeof(entry->id));
299 300 301
	git__free(entry);
}

302
unsigned int git_index__create_mode(unsigned int mode)
303 304 305
{
	if (S_ISLNK(mode))
		return S_IFLNK;
306

307 308
	if (S_ISDIR(mode) || (mode & S_IFMT) == (S_IFLNK | S_IFDIR))
		return (S_IFLNK | S_IFDIR);
309

310
	return S_IFREG | GIT_PERMS_CANONICAL(mode);
311 312
}

313 314 315 316 317 318 319 320 321
static unsigned int index_merge_mode(
	git_index *index, git_index_entry *existing, unsigned int mode)
{
	if (index->no_symlinks && S_ISREG(mode) &&
		existing && S_ISLNK(existing->mode))
		return existing->mode;

	if (index->distrust_filemode && S_ISREG(mode))
		return (existing && S_ISREG(existing->mode)) ?
322
			existing->mode : git_index__create_mode(0666);
323

324
	return git_index__create_mode(mode);
325 326
}

327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
static int index_sort_if_needed(git_index *index, bool need_lock)
{
	/* not truly threadsafe because between when this checks and/or
	 * sorts the array another thread could come in and unsort it
	 */

	if (git_vector_is_sorted(&index->entries))
		return 0;

	if (need_lock && git_mutex_lock(&index->lock) < 0) {
		giterr_set(GITERR_OS, "Unable to lock index");
		return -1;
	}

	git_vector_sort(&index->entries);

	if (need_lock)
		git_mutex_unlock(&index->lock);

	return 0;
}

349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
GIT_INLINE(int) index_find_in_entries(
	size_t *out, git_vector *entries, git_vector_cmp entry_srch,
	const char *path, size_t path_len, int stage)
{
	struct entry_srch_key srch_key;
	srch_key.path = path;
	srch_key.pathlen = !path_len ? strlen(path) : path_len;
	srch_key.stage = stage;
	return git_vector_bsearch2(out, entries, entry_srch, &srch_key);
}

GIT_INLINE(int) index_find(
	size_t *out, git_index *index,
	const char *path, size_t path_len, int stage, bool need_lock)
{
	if (index_sort_if_needed(index, need_lock) < 0)
		return -1;

	return index_find_in_entries(
		out, &index->entries, index->entries_search, path, path_len, stage);
}

371
void git_index__set_ignore_case(git_index *index, bool ignore_case)
372
{
373 374
	index->ignore_case = ignore_case;

375 376 377 378 379 380 381 382 383 384 385
	if (ignore_case) {
		index->entries_cmp_path    = git__strcasecmp_cb;
		index->entries_search      = git_index_entry_isrch;
		index->entries_search_path = index_entry_isrch_path;
		index->reuc_search         = reuc_isrch;
	} else {
		index->entries_cmp_path    = git__strcmp_cb;
		index->entries_search      = git_index_entry_srch;
		index->entries_search_path = index_entry_srch_path;
		index->reuc_search         = reuc_srch;
	}
386

387 388
	git_vector_set_cmp(&index->entries,
		ignore_case ? git_index_entry_icmp : git_index_entry_cmp);
389
	index_sort_if_needed(index, true);
Edward Thomson committed
390

391
	git_vector_set_cmp(&index->reuc, ignore_case ? reuc_icmp : reuc_cmp);
Edward Thomson committed
392
	git_vector_sort(&index->reuc);
393 394
}

395
int git_index_open(git_index **index_out, const char *index_path)
396 397
{
	git_index *index;
398
	int error = -1;
399

400
	assert(index_out);
401

402 403
	index = git__calloc(1, sizeof(git_index));
	GITERR_CHECK_ALLOC(index);
404

405 406 407 408 409 410
	if (git_mutex_init(&index->lock)) {
		giterr_set(GITERR_OS, "Failed to initialize lock");
		git__free(index);
		return -1;
	}

411 412
	git_pool_init(&index->tree_pool, 1, 0);

413 414
	if (index_path != NULL) {
		index->index_file_path = git__strdup(index_path);
415 416
		if (!index->index_file_path)
			goto fail;
417 418 419 420 421

		/* Check if index file is stored on disk already */
		if (git_path_exists(index->index_file_path) == true)
			index->on_disk = 1;
	}
422

423
	if (git_vector_init(&index->entries, 32, git_index_entry_cmp) < 0 ||
424 425 426
		git_vector_init(&index->names, 8, conflict_name_cmp) < 0 ||
		git_vector_init(&index->reuc, 8, reuc_cmp) < 0 ||
		git_vector_init(&index->deleted, 8, git_index_entry_cmp) < 0)
427
		goto fail;
428

429 430 431
	index->entries_cmp_path = git__strcmp_cb;
	index->entries_search = git_index_entry_srch;
	index->entries_search_path = index_entry_srch_path;
Edward Thomson committed
432
	index->reuc_search = reuc_srch;
433

434 435
	if (index_path != NULL && (error = git_index_read(index, true)) < 0)
		goto fail;
436

Vicent Marti committed
437
	*index_out = index;
438
	GIT_REFCOUNT_INC(index);
439

440
	return 0;
441 442

fail:
443
	git_pool_clear(&index->tree_pool);
444 445
	git_index_free(index);
	return error;
446 447
}

448 449 450 451 452
int git_index_new(git_index **out)
{
	return git_index_open(out, NULL);
}

453
static void index_free(git_index *index)
454
{
455 456 457 458 459
	/* index iterators increment the refcount of the index, so if we
	 * get here then there should be no outstanding iterators.
	 */
	assert(!git_atomic_get(&index->readers));

460 461
	git_index_clear(index);
	git_vector_free(&index->entries);
Edward Thomson committed
462
	git_vector_free(&index->names);
Edward Thomson committed
463
	git_vector_free(&index->reuc);
464
	git_vector_free(&index->deleted);
465

466
	git__free(index->index_file_path);
467
	git_mutex_free(&index->lock);
468

469
	git__memzero(index, sizeof(*index));
470
	git__free(index);
471 472
}

473 474
void git_index_free(git_index *index)
{
475
	if (index == NULL)
476 477
		return;

478
	GIT_REFCOUNT_DEC(index, index_free);
479 480
}

481 482
/* call with locked index */
static void index_free_deleted(git_index *index)
483
{
484
	int readers = (int)git_atomic_get(&index->readers);
485
	size_t i;
486

487
	if (readers > 0 || !index->deleted.length)
488 489
		return;

490 491 492 493
	for (i = 0; i < index->deleted.length; ++i) {
		git_index_entry *ie = git__swap(index->deleted.contents[i], NULL);
		index_entry_free(ie);
	}
494 495 496 497

	git_vector_clear(&index->deleted);
}

498 499
/* call with locked index */
static int index_remove_entry(git_index *index, size_t pos)
500 501 502 503 504 505 506 507 508 509
{
	int error = 0;
	git_index_entry *entry = git_vector_get(&index->entries, pos);

	if (entry != NULL)
		git_tree_cache_invalidate_path(index->tree, entry->path);

	error = git_vector_remove(&index->entries, pos);

	if (!error) {
510
		if (git_atomic_get(&index->readers) > 0) {
511
			error = git_vector_insert(&index->deleted, entry);
512
		} else {
513
			index_entry_free(entry);
514
		}
515 516 517
	}

	return error;
518
}
519

520
int git_index_clear(git_index *index)
521
{
522 523
	int error = 0;

524 525
	assert(index);

526
	index->tree = NULL;
527
	git_pool_clear(&index->tree_pool);
528

529 530 531 532 533 534
	if (git_mutex_lock(&index->lock) < 0) {
		giterr_set(GITERR_OS, "Failed to lock index");
		return -1;
	}

	while (!error && index->entries.length > 0)
535
		error = index_remove_entry(index, index->entries.length - 1);
536 537
	index_free_deleted(index);

538
	git_index_reuc_clear(index);
Edward Thomson committed
539
	git_index_name_clear(index);
nulltoken committed
540

541
	git_futils_filestamp_set(&index->stamp, NULL);
542

543 544
	git_mutex_unlock(&index->lock);

545
	return error;
546 547
}

548 549 550 551 552 553
static int create_index_error(int error, const char *msg)
{
	giterr_set(GITERR_INDEX, msg);
	return error;
}

Russell Belfer committed
554
int git_index_set_caps(git_index *index, int caps)
555
{
Linquize committed
556
	unsigned int old_ignore_case;
557

558 559
	assert(index);

560 561
	old_ignore_case = index->ignore_case;

562
	if (caps == GIT_INDEXCAP_FROM_OWNER) {
563
		git_repository *repo = INDEX_OWNER(index);
564 565
		int val;

566 567 568
		if (!repo)
			return create_index_error(
				-1, "Cannot access repository to set index caps");
569

570
		if (!git_repository__cvar(&val, repo, GIT_CVAR_IGNORECASE))
571
			index->ignore_case = (val != 0);
572
		if (!git_repository__cvar(&val, repo, GIT_CVAR_FILEMODE))
573
			index->distrust_filemode = (val == 0);
574
		if (!git_repository__cvar(&val, repo, GIT_CVAR_SYMLINKS))
575
			index->no_symlinks = (val == 0);
576 577 578 579 580 581 582
	}
	else {
		index->ignore_case = ((caps & GIT_INDEXCAP_IGNORE_CASE) != 0);
		index->distrust_filemode = ((caps & GIT_INDEXCAP_NO_FILEMODE) != 0);
		index->no_symlinks = ((caps & GIT_INDEXCAP_NO_SYMLINKS) != 0);
	}

583
	if (old_ignore_case != index->ignore_case) {
Linquize committed
584
		git_index__set_ignore_case(index, (bool)index->ignore_case);
585 586
	}

587 588 589
	return 0;
}

Russell Belfer committed
590
int git_index_caps(const git_index *index)
591 592 593 594 595 596
{
	return ((index->ignore_case ? GIT_INDEXCAP_IGNORE_CASE : 0) |
			(index->distrust_filemode ? GIT_INDEXCAP_NO_FILEMODE : 0) |
			(index->no_symlinks ? GIT_INDEXCAP_NO_SYMLINKS : 0));
}

597
int git_index_read(git_index *index, int force)
598
{
599
	int error = 0, updated;
600
	git_buf buffer = GIT_BUF_INIT;
601
	git_futils_filestamp stamp = index->stamp;
602

603 604
	if (!index->index_file_path)
		return create_index_error(-1,
605
			"Failed to read index: The index is in-memory only");
606

607 608 609
	index->on_disk = git_path_exists(index->index_file_path);

	if (!index->on_disk) {
610
		if (force)
611
			return git_index_clear(index);
612
		return 0;
613 614
	}

615
	updated = git_futils_filestamp_check(&stamp, index->index_file_path);
616 617 618 619 620
	if (updated < 0) {
		giterr_set(
			GITERR_INDEX,
			"Failed to read index: '%s' no longer exists",
			index->index_file_path);
621
		return updated;
622 623 624
	}
	if (!updated && !force)
		return 0;
625 626

	error = git_futils_readbuffer(&buffer, index->index_file_path);
627 628
	if (error < 0)
		return error;
629

630 631 632
	index->tree = NULL;
	git_pool_clear(&index->tree_pool);

633 634 635 636
	error = git_index_clear(index);

	if (!error)
		error = parse_index(index, buffer.ptr, buffer.size);
637

638 639
	if (!error)
		git_futils_filestamp_set(&index->stamp, &stamp);
640

641
	git_buf_free(&buffer);
642 643 644
	return error;
}

645 646 647 648 649 650 651
int git_index__changed_relative_to(
	git_index *index, const git_futils_filestamp *fs)
{
	/* attempt to update index (ignoring errors) */
	if (git_index_read(index, false) < 0)
		giterr_clear();

652 653 654
	return (index->stamp.mtime != fs->mtime ||
			index->stamp.size != fs->size ||
			index->stamp.ino != fs->ino);
655 656
}

657 658
int git_index_write(git_index *index)
{
659
	git_indexwriter writer = GIT_INDEXWRITER_INIT;
660
	int error;
661

662 663
	if ((error = git_indexwriter_init(&writer, index)) == 0)
		error = git_indexwriter_commit(&writer);
664

665
	git_indexwriter_cleanup(&writer);
666

667
	return error;
668
}
669

Jacques Germishuys committed
670
const char * git_index_path(const git_index *index)
671 672 673 674
{
	assert(index);
	return index->index_file_path;
}
675

676 677 678 679 680 681
int git_index_write_tree(git_oid *oid, git_index *index)
{
	git_repository *repo;

	assert(oid && index);

682
	repo = INDEX_OWNER(index);
683

684 685
	if (repo == NULL)
		return create_index_error(-1, "Failed to write tree. "
686 687 688 689 690
		  "The index file is not backed up by an existing repository");

	return git_tree__write_index(oid, index, repo);
}

691 692
int git_index_write_tree_to(
	git_oid *oid, git_index *index, git_repository *repo)
693 694 695 696 697
{
	assert(oid && index && repo);
	return git_tree__write_index(oid, index, repo);
}

698
size_t git_index_entrycount(const git_index *index)
699 700
{
	assert(index);
701
	return index->entries.length;
702 703
}

704 705
const git_index_entry *git_index_get_byindex(
	git_index *index, size_t n)
706 707
{
	assert(index);
708 709
	if (index_sort_if_needed(index, true) < 0)
		return NULL;
Edward Thomson committed
710
	return git_vector_get(&index->entries, n);
711 712
}

713 714
const git_index_entry *git_index_get_bypath(
	git_index *index, const char *path, int stage)
715
{
716
	size_t pos;
Edward Thomson committed
717 718 719

	assert(index);

720
	if (index_find(&pos, index, path, 0, stage, true) < 0) {
721
		giterr_set(GITERR_INDEX, "Index does not contain %s", path);
Edward Thomson committed
722
		return NULL;
723
	}
Edward Thomson committed
724 725

	return git_index_get_byindex(index, pos);
726 727
}

728 729
void git_index_entry__init_from_stat(
	git_index_entry *entry, struct stat *st, bool trust_mode)
730 731 732 733 734 735 736
{
	entry->ctime.seconds = (git_time_t)st->st_ctime;
	entry->mtime.seconds = (git_time_t)st->st_mtime;
	/* entry->mtime.nanoseconds = st->st_mtimensec; */
	/* entry->ctime.nanoseconds = st->st_ctimensec; */
	entry->dev  = st->st_rdev;
	entry->ino  = st->st_ino;
737
	entry->mode = (!trust_mode && S_ISREG(st->st_mode)) ?
738
		git_index__create_mode(0666) : git_index__create_mode(st->st_mode);
739 740 741 742 743
	entry->uid  = st->st_uid;
	entry->gid  = st->st_gid;
	entry->file_size = st->st_size;
}

744 745 746 747
static int index_entry_create(
	git_index_entry **out,
	git_repository *repo,
	const char *path)
748
{
749
	size_t pathlen = strlen(path), alloclen;
750 751
	struct entry_internal *entry;

752 753 754
	if (!git_path_isvalid(repo, path,
		GIT_PATH_REJECT_DEFAULTS | GIT_PATH_REJECT_DOT_GIT)) {
		giterr_set(GITERR_INDEX, "Invalid path: '%s'", path);
755
		return -1;
756
	}
757

758 759 760
	GITERR_CHECK_ALLOC_ADD(&alloclen, sizeof(struct entry_internal), pathlen);
	GITERR_CHECK_ALLOC_ADD(&alloclen, alloclen, 1);
	entry = git__calloc(1, alloclen);
761
	GITERR_CHECK_ALLOC(entry);
762 763 764 765 766

	entry->pathlen = pathlen;
	memcpy(entry->path, path, pathlen);
	entry->entry.path = entry->path;

767 768
	*out = (git_index_entry *)entry;
	return 0;
769 770
}

771
static int index_entry_init(
772 773 774
	git_index_entry **entry_out,
	git_index *index,
	const char *rel_path)
775
{
776
	int error = 0;
777
	git_index_entry *entry = NULL;
778 779
	struct stat st;
	git_oid oid;
780

781 782 783 784 785
	if (INDEX_OWNER(index) == NULL)
		return create_index_error(-1,
			"Could not initialize index entry. "
			"Index is not backed up by an existing repository.");

786
	if (index_entry_create(&entry, INDEX_OWNER(index), rel_path) < 0)
787 788
		return -1;

789 790 791
	/* write the blob to disk and get the oid and stat info */
	error = git_blob__create_from_paths(
		&oid, &st, INDEX_OWNER(index), NULL, rel_path, 0, true);
792

793 794 795 796
	if (error < 0) {
		index_entry_free(entry);
		return error;
	}
797

798
	entry->id = oid;
799
	git_index_entry__init_from_stat(entry, &st, !index->distrust_filemode);
800

801
	*entry_out = (git_index_entry *)entry;
802
	return 0;
803 804
}

805 806
static git_index_reuc_entry *reuc_entry_alloc(const char *path)
{
807
	size_t pathlen = strlen(path),
808 809
		structlen = sizeof(struct reuc_entry_internal),
		alloclen;
810 811
	struct reuc_entry_internal *entry;

812 813
	if (GIT_ADD_SIZET_OVERFLOW(&alloclen, structlen, pathlen) ||
		GIT_ADD_SIZET_OVERFLOW(&alloclen, alloclen, 1))
814 815
		return NULL;

816
	entry = git__calloc(1, alloclen);
817 818 819 820 821 822 823 824 825 826
	if (!entry)
		return NULL;

	entry->pathlen = pathlen;
	memcpy(entry->path, path, pathlen);
	entry->entry.path = entry->path;

	return (git_index_reuc_entry *)entry;
}

Edward Thomson committed
827 828
static int index_entry_reuc_init(git_index_reuc_entry **reuc_out,
	const char *path,
Edward Thomson committed
829 830 831
	int ancestor_mode, const git_oid *ancestor_oid,
	int our_mode, const git_oid *our_oid,
	int their_mode, const git_oid *their_oid)
Edward Thomson committed
832 833 834 835 836
{
	git_index_reuc_entry *reuc = NULL;

	assert(reuc_out && path);

837
	*reuc_out = reuc = reuc_entry_alloc(path);
Edward Thomson committed
838 839
	GITERR_CHECK_ALLOC(reuc);

840 841
	if ((reuc->mode[0] = ancestor_mode) > 0)
		git_oid_cpy(&reuc->oid[0], ancestor_oid);
Edward Thomson committed
842

843 844
	if ((reuc->mode[1] = our_mode) > 0)
		git_oid_cpy(&reuc->oid[1], our_oid);
Edward Thomson committed
845

846 847
	if ((reuc->mode[2] = their_mode) > 0)
		git_oid_cpy(&reuc->oid[2], their_oid);
Edward Thomson committed
848 849 850 851

	return 0;
}

852 853
static void index_entry_cpy(git_index_entry *tgt, const git_index_entry *src)
{
854
	const char *tgt_path = tgt->path;
855 856 857 858
	memcpy(tgt, src, sizeof(*tgt));
	tgt->path = tgt_path; /* reset to existing path data */
}

859 860 861 862
static int index_entry_dup(
	git_index_entry **out,
	git_repository *repo,
	const git_index_entry *src)
863 864 865
{
	git_index_entry *entry;

866 867 868 869 870
	if (!src) {
		*out = NULL;
		return 0;
	}

871
	if (index_entry_create(&entry, repo, src->path) < 0)
872
		return -1;
873

874
	index_entry_cpy(entry, src);
875
	*out = entry;
876
	return 0;
877 878
}

879
static int has_file_name(git_index *index,
880
	 const git_index_entry *entry, size_t pos, int ok_to_replace)
881 882
{
	int retval = 0;
883 884 885
	size_t len = strlen(entry->path);
	int stage = GIT_IDXENTRY_STAGE(entry);
	const char *name = entry->path;
886

887
	while (pos < index->entries.length) {
888
		struct entry_internal *p = index->entries.contents[pos++];
889

890
		if (len >= p->pathlen)
891
			break;
892
		if (memcmp(name, p->path, len))
893
			break;
894
		if (GIT_IDXENTRY_STAGE(&p->entry) != stage)
895
			continue;
896
		if (p->path[len] != '/')
897 898 899 900
			continue;
		retval = -1;
		if (!ok_to_replace)
			break;
901

902
		if (index_remove_entry(index, --pos) < 0)
903
			break;
904 905 906 907 908 909 910 911 912 913 914 915
	}
	return retval;
}

/*
 * Do we have another file with a pathname that is a proper
 * subset of the name we're trying to add?
 */
static int has_dir_name(git_index *index,
		const git_index_entry *entry, int ok_to_replace)
{
	int retval = 0;
916 917 918
	int stage = GIT_IDXENTRY_STAGE(entry);
	const char *name = entry->path;
	const char *slash = name + strlen(name);
919 920

	for (;;) {
921
		size_t len, pos;
922 923 924 925

		for (;;) {
			if (*--slash == '/')
				break;
926
			if (slash <= entry->path)
927 928 929 930
				return retval;
		}
		len = slash - name;

931
		if (!index_find(&pos, index, name, len, stage, false)) {
932 933 934 935
			retval = -1;
			if (!ok_to_replace)
				break;

936
			if (index_remove_entry(index, pos) < 0)
937
				break;
938
			continue;
939 940 941 942 943 944 945
		}

		/*
		 * Trivial optimization: if we find an entry that
		 * already matches the sub-directory, then we know
		 * we're ok, and we can exit.
		 */
946 947
		for (; pos < index->entries.length; ++pos) {
			struct entry_internal *p = index->entries.contents[pos];
948

949 950
			if (p->pathlen <= len ||
			    p->path[len] != '/' ||
951
			    memcmp(p->path, name, len))
952
				break; /* not our subdirectory */
953

954
			if (GIT_IDXENTRY_STAGE(&p->entry) == stage)
955 956 957
				return retval;
		}
	}
958

959 960
	return retval;
}
961

962
static int check_file_directory_collision(git_index *index,
963 964 965 966 967 968
		git_index_entry *entry, size_t pos, int ok_to_replace)
{
	int retval = has_file_name(index, entry, pos, ok_to_replace);
	retval = retval + has_dir_name(index, entry, ok_to_replace);

	if (retval) {
969 970
		giterr_set(GITERR_INDEX,
			"'%s' appears as both a file and a directory", entry->path);
971 972 973 974 975
		return -1;
	}

	return 0;
}
976

977 978 979 980 981 982 983 984 985
static int index_no_dups(void **old, void *new)
{
	const git_index_entry *entry = new;
	GIT_UNUSED(old);
	giterr_set(GITERR_INDEX, "'%s' appears multiple times at stage %d",
		entry->path, GIT_IDXENTRY_STAGE(entry));
	return GIT_EEXISTS;
}

986 987 988 989 990 991 992
/* index_insert takes ownership of the new entry - if it can't insert
 * it, then it will return an error **and also free the entry**.  When
 * it replaces an existing entry, it will update the entry_ptr with the
 * actual entry in the index (and free the passed in one).
 */
static int index_insert(
	git_index *index, git_index_entry **entry_ptr, int replace)
993
{
994
	int error = 0;
995
	size_t path_length, position;
996
	git_index_entry *existing = NULL, *entry;
997

998 999 1000
	assert(index && entry_ptr);

	entry = *entry_ptr;
1001

1002
	/* make sure that the path length flag is correct */
1003
	path_length = ((struct entry_internal *)entry)->pathlen;
1004

1005
	entry->flags &= ~GIT_IDXENTRY_NAMEMASK;
1006 1007

	if (path_length < GIT_IDXENTRY_NAMEMASK)
1008
		entry->flags |= path_length & GIT_IDXENTRY_NAMEMASK;
1009
	else
Edward Thomson committed
1010
		entry->flags |= GIT_IDXENTRY_NAMEMASK;
1011

1012
	if (git_mutex_lock(&index->lock) < 0) {
1013
		giterr_set(GITERR_OS, "Unable to acquire index lock");
1014
		return -1;
1015 1016 1017 1018
	}

	git_vector_sort(&index->entries);

1019
	/* look if an entry with this path already exists */
1020
	if (!index_find(
1021
			&position, index, entry->path, 0, GIT_IDXENTRY_STAGE(entry), false)) {
1022
		existing = index->entries.contents[position];
1023
		/* update filemode to existing values if stat is not trusted */
1024
		entry->mode = index_merge_mode(index, existing, entry->mode);
1025 1026
	}

1027
	/* look for tree / blob name collisions, removing conflicts if requested */
1028 1029
	error = check_file_directory_collision(index, entry, position, replace);
	if (error < 0)
1030
		/* skip changes */;
1031 1032 1033 1034

	/* if we are replacing an existing item, overwrite the existing entry
	 * and return it in place of the passed in one.
	 */
1035 1036 1037
	else if (existing) {
		if (replace)
			index_entry_cpy(existing, entry);
1038
		index_entry_free(entry);
1039
		*entry_ptr = entry = existing;
1040
	}
1041
	else {
1042 1043 1044
		/* if replace is not requested or no existing entry exists, insert
		 * at the sorted position.  (Since we re-sort after each insert to
		 * check for dups, this is actually cheaper in the long run.)
1045
		 */
1046
		error = git_vector_insert_sorted(&index->entries, entry, index_no_dups);
1047
	}
1048

1049 1050 1051 1052
	if (error < 0) {
		index_entry_free(*entry_ptr);
		*entry_ptr = NULL;
	}
1053

1054 1055
	git_mutex_unlock(&index->lock);

1056
	return error;
1057 1058
}

Edward Thomson committed
1059
static int index_conflict_to_reuc(git_index *index, const char *path)
1060
{
1061
	const git_index_entry *conflict_entries[3];
Edward Thomson committed
1062
	int ancestor_mode, our_mode, their_mode;
Edward Thomson committed
1063
	git_oid const *ancestor_oid, *our_oid, *their_oid;
1064
	int ret;
1065

Edward Thomson committed
1066 1067
	if ((ret = git_index_conflict_get(&conflict_entries[0],
		&conflict_entries[1], &conflict_entries[2], index, path)) < 0)
1068
		return ret;
1069

Edward Thomson committed
1070 1071 1072
	ancestor_mode = conflict_entries[0] == NULL ? 0 : conflict_entries[0]->mode;
	our_mode = conflict_entries[1] == NULL ? 0 : conflict_entries[1]->mode;
	their_mode = conflict_entries[2] == NULL ? 0 : conflict_entries[2]->mode;
1073

1074 1075 1076
	ancestor_oid = conflict_entries[0] == NULL ? NULL : &conflict_entries[0]->id;
	our_oid = conflict_entries[1] == NULL ? NULL : &conflict_entries[1]->id;
	their_oid = conflict_entries[2] == NULL ? NULL : &conflict_entries[2]->id;
Edward Thomson committed
1077 1078 1079 1080 1081 1082

	if ((ret = git_index_reuc_add(index, path, ancestor_mode, ancestor_oid,
		our_mode, our_oid, their_mode, their_oid)) >= 0)
		ret = git_index_conflict_remove(index, path);

	return ret;
1083 1084
}

1085 1086 1087 1088 1089 1090 1091 1092 1093
static bool valid_filemode(const int filemode)
{
	return (filemode == GIT_FILEMODE_BLOB ||
		filemode == GIT_FILEMODE_BLOB_EXECUTABLE ||
		filemode == GIT_FILEMODE_LINK ||
		filemode == GIT_FILEMODE_COMMIT);
}

int git_index_add_frombuffer(
1094
    git_index *index, const git_index_entry *source_entry,
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
    const void *buffer, size_t len)
{
	git_index_entry *entry = NULL;
	int error = 0;
	git_oid id;

	assert(index && source_entry->path);

	if (INDEX_OWNER(index) == NULL)
		return create_index_error(-1,
			"Could not initialize index entry. "
			"Index is not backed up by an existing repository.");

	if (!valid_filemode(source_entry->mode)) {
		giterr_set(GITERR_INDEX, "invalid filemode");
		return -1;
	}

	if (index_entry_dup(&entry, INDEX_OWNER(index), source_entry) < 0)
		return -1;

	error = git_blob_create_frombuffer(&id, INDEX_OWNER(index), buffer, len);
	if (error < 0) {
		index_entry_free(entry);
		return error;
	}

	git_oid_cpy(&entry->id, &id);
	entry->file_size = len;

	if ((error = index_insert(index, &entry, 1)) < 0)
		return error;

	/* Adding implies conflict was resolved, move conflict entries to REUC */
	if ((error = index_conflict_to_reuc(index, entry->path)) < 0 && error != GIT_ENOTFOUND)
		return error;

	git_tree_cache_invalidate_path(index->tree, entry->path);
	return 0;
}


1137
int git_index_add_bypath(git_index *index, const char *path)
1138
{
Edward Thomson committed
1139 1140 1141 1142 1143 1144
	git_index_entry *entry = NULL;
	int ret;

	assert(index && path);

	if ((ret = index_entry_init(&entry, index, path)) < 0 ||
1145 1146
		(ret = index_insert(index, &entry, 1)) < 0)
		return ret;
Edward Thomson committed
1147 1148 1149

	/* Adding implies conflict was resolved, move conflict entries to REUC */
	if ((ret = index_conflict_to_reuc(index, path)) < 0 && ret != GIT_ENOTFOUND)
1150
		return ret;
Edward Thomson committed
1151 1152 1153

	git_tree_cache_invalidate_path(index->tree, entry->path);
	return 0;
1154 1155
}

1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
int git_index_remove_bypath(git_index *index, const char *path)
{
	int ret;

	assert(index && path);

	if (((ret = git_index_remove(index, path, 0)) < 0 &&
		ret != GIT_ENOTFOUND) ||
		((ret = index_conflict_to_reuc(index, path)) < 0 &&
		ret != GIT_ENOTFOUND))
		return ret;

	return 0;
}

1171

Edward Thomson committed
1172
int git_index_add(git_index *index, const git_index_entry *source_entry)
1173 1174 1175 1176
{
	git_index_entry *entry = NULL;
	int ret;

1177
	assert(index && source_entry && source_entry->path);
1178

1179 1180 1181 1182 1183
	if (!valid_filemode(source_entry->mode)) {
		giterr_set(GITERR_INDEX, "invalid filemode");
		return -1;
	}

1184
	if ((ret = index_entry_dup(&entry, INDEX_OWNER(index), source_entry)) < 0 ||
1185
		(ret = index_insert(index, &entry, 1)) < 0)
1186
		return ret;
1187

1188
	git_tree_cache_invalidate_path(index->tree, entry->path);
1189
	return 0;
1190 1191
}

Edward Thomson committed
1192
int git_index_remove(git_index *index, const char *path, int stage)
1193
{
1194
	int error;
1195
	size_t position;
1196

1197 1198 1199 1200 1201
	if (git_mutex_lock(&index->lock) < 0) {
		giterr_set(GITERR_OS, "Failed to lock index");
		return -1;
	}

1202
	if (index_find(&position, index, path, 0, stage, false) < 0) {
1203 1204 1205 1206 1207
		giterr_set(
			GITERR_INDEX, "Index does not contain %s at stage %d", path, stage);
		error = GIT_ENOTFOUND;
	} else {
		error = index_remove_entry(index, position);
1208
	}
Edward Thomson committed
1209

1210 1211
	git_mutex_unlock(&index->lock);
	return error;
1212
}
1213

1214 1215 1216 1217 1218 1219 1220
int git_index_remove_directory(git_index *index, const char *dir, int stage)
{
	git_buf pfx = GIT_BUF_INIT;
	int error = 0;
	size_t pos;
	git_index_entry *entry;

1221 1222
	if (git_mutex_lock(&index->lock) < 0) {
		giterr_set(GITERR_OS, "Failed to lock index");
1223
		return -1;
1224
	}
1225

1226 1227
	if (!(error = git_buf_sets(&pfx, dir)) &&
		!(error = git_path_to_dir(&pfx)))
1228
		index_find(&pos, index, pfx.ptr, pfx.size, GIT_INDEX_STAGE_ANY, false);
1229

1230
	while (!error) {
1231 1232 1233 1234
		entry = git_vector_get(&index->entries, pos);
		if (!entry || git__prefixcmp(entry->path, pfx.ptr) != 0)
			break;

1235
		if (GIT_IDXENTRY_STAGE(entry) != stage) {
1236 1237 1238 1239
			++pos;
			continue;
		}

1240
		error = index_remove_entry(index, pos);
1241

1242
		/* removed entry at 'pos' so we don't need to increment */
1243 1244
	}

1245
	git_mutex_unlock(&index->lock);
1246 1247 1248 1249 1250
	git_buf_free(&pfx);

	return error;
}

1251
int git_index__find_pos(
1252 1253 1254
	size_t *out, git_index *index, const char *path, size_t path_len, int stage)
{
	assert(index && path);
1255
	return index_find(out, index, path, path_len, stage, true);
Edward Thomson committed
1256 1257
}

1258
int git_index_find(size_t *at_pos, git_index *index, const char *path)
1259
{
1260
	size_t pos;
Edward Thomson committed
1261 1262 1263

	assert(index && path);

1264 1265 1266 1267 1268
	if (git_mutex_lock(&index->lock) < 0) {
		giterr_set(GITERR_OS, "Failed to lock index");
		return -1;
	}

1269 1270
	if (git_vector_bsearch2(
			&pos, &index->entries, index->entries_search_path, path) < 0) {
1271
		git_mutex_unlock(&index->lock);
1272
		giterr_set(GITERR_INDEX, "Index does not contain %s", path);
1273
		return GIT_ENOTFOUND;
1274
	}
Edward Thomson committed
1275 1276

	/* Since our binary search only looked at path, we may be in the
1277 1278
	 * middle of a list of stages.
	 */
1279 1280
	for (; pos > 0; --pos) {
		const git_index_entry *prev = git_vector_get(&index->entries, pos - 1);
Edward Thomson committed
1281 1282 1283 1284 1285

		if (index->entries_cmp_path(prev->path, path) != 0)
			break;
	}

1286 1287 1288
	if (at_pos)
		*at_pos = pos;

1289
	git_mutex_unlock(&index->lock);
1290
	return 0;
1291 1292
}

Edward Thomson committed
1293 1294 1295 1296 1297 1298
int git_index_conflict_add(git_index *index,
	const git_index_entry *ancestor_entry,
	const git_index_entry *our_entry,
	const git_index_entry *their_entry)
{
	git_index_entry *entries[3] = { 0 };
1299
	unsigned short i;
Edward Thomson committed
1300 1301 1302 1303
	int ret = 0;

	assert (index);

1304 1305 1306
	if ((ret = index_entry_dup(&entries[0], INDEX_OWNER(index), ancestor_entry)) < 0 ||
		(ret = index_entry_dup(&entries[1], INDEX_OWNER(index), our_entry)) < 0 ||
		(ret = index_entry_dup(&entries[2], INDEX_OWNER(index), their_entry)) < 0)
1307
		goto on_error;
Edward Thomson committed
1308 1309 1310 1311 1312 1313

	for (i = 0; i < 3; i++) {
		if (entries[i] == NULL)
			continue;

		/* Make sure stage is correct */
1314
		GIT_IDXENTRY_STAGE_SET(entries[i], i + 1);
Edward Thomson committed
1315

1316
		if ((ret = index_insert(index, &entries[i], 1)) < 0)
Edward Thomson committed
1317
			goto on_error;
1318 1319

		entries[i] = NULL; /* don't free if later entry fails */
Edward Thomson committed
1320 1321
	}

nulltoken committed
1322
	return 0;
Edward Thomson committed
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332

on_error:
	for (i = 0; i < 3; i++) {
		if (entries[i] != NULL)
			index_entry_free(entries[i]);
	}

	return ret;
}

1333 1334 1335 1336 1337 1338
static int index_conflict__get_byindex(
	const git_index_entry **ancestor_out,
	const git_index_entry **our_out,
	const git_index_entry **their_out,
	git_index *index,
	size_t n)
Edward Thomson committed
1339
{
1340 1341 1342 1343
	const git_index_entry *conflict_entry;
	const char *path = NULL;
	size_t count;
	int stage, len = 0;
Edward Thomson committed
1344

1345
	assert(ancestor_out && our_out && their_out && index);
1346

Edward Thomson committed
1347 1348 1349 1350
	*ancestor_out = NULL;
	*our_out = NULL;
	*their_out = NULL;

1351 1352
	for (count = git_index_entrycount(index); n < count; ++n) {
		conflict_entry = git_vector_get(&index->entries, n);
Edward Thomson committed
1353

1354
		if (path && index->entries_cmp_path(conflict_entry->path, path) != 0)
Edward Thomson committed
1355 1356
			break;

1357
		stage = GIT_IDXENTRY_STAGE(conflict_entry);
1358
		path = conflict_entry->path;
1359

Edward Thomson committed
1360 1361 1362
		switch (stage) {
		case 3:
			*their_out = conflict_entry;
1363
			len++;
Edward Thomson committed
1364 1365 1366
			break;
		case 2:
			*our_out = conflict_entry;
1367
			len++;
Edward Thomson committed
1368 1369 1370
			break;
		case 1:
			*ancestor_out = conflict_entry;
1371
			len++;
Edward Thomson committed
1372 1373 1374 1375 1376 1377
			break;
		default:
			break;
		};
	}

1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
	return len;
}

int git_index_conflict_get(
	const git_index_entry **ancestor_out,
	const git_index_entry **our_out,
	const git_index_entry **their_out,
	git_index *index,
	const char *path)
{
	size_t pos;
	int len = 0;

	assert(ancestor_out && our_out && their_out && index && path);

	*ancestor_out = NULL;
	*our_out = NULL;
	*their_out = NULL;

	if (git_index_find(&pos, index, path) < 0)
		return GIT_ENOTFOUND;

	if ((len = index_conflict__get_byindex(
		ancestor_out, our_out, their_out, index, pos)) < 0)
		return len;
	else if (len == 0)
		return GIT_ENOTFOUND;

	return 0;
Edward Thomson committed
1407 1408
}

1409
static int index_conflict_remove(git_index *index, const char *path)
Edward Thomson committed
1410
{
1411
	size_t pos = 0;
Edward Thomson committed
1412
	git_index_entry *conflict_entry;
1413
	int error = 0;
Edward Thomson committed
1414

1415
	if (path != NULL && git_index_find(&pos, index, path) < 0)
1416
		return GIT_ENOTFOUND;
Edward Thomson committed
1417

1418 1419 1420 1421 1422
	if (git_mutex_lock(&index->lock) < 0) {
		giterr_set(GITERR_OS, "Unable to lock index");
		return -1;
	}

1423
	while ((conflict_entry = git_vector_get(&index->entries, pos)) != NULL) {
Edward Thomson committed
1424

1425 1426
		if (path != NULL &&
			index->entries_cmp_path(conflict_entry->path, path) != 0)
Edward Thomson committed
1427 1428
			break;

1429
		if (GIT_IDXENTRY_STAGE(conflict_entry) == 0) {
Edward Thomson committed
1430 1431 1432 1433
			pos++;
			continue;
		}

1434
		if ((error = index_remove_entry(index, pos)) < 0)
1435
			break;
Edward Thomson committed
1436 1437
	}

1438 1439
	git_mutex_unlock(&index->lock);

1440
	return error;
Edward Thomson committed
1441 1442
}

1443
int git_index_conflict_remove(git_index *index, const char *path)
Edward Thomson committed
1444
{
1445 1446
	assert(index && path);
	return index_conflict_remove(index, path);
Edward Thomson committed
1447 1448
}

1449
int git_index_conflict_cleanup(git_index *index)
Edward Thomson committed
1450 1451
{
	assert(index);
1452
	return index_conflict_remove(index, NULL);
Edward Thomson committed
1453 1454
}

1455
int git_index_has_conflicts(const git_index *index)
1456
{
1457
	size_t i;
1458 1459 1460 1461 1462
	git_index_entry *entry;

	assert(index);

	git_vector_foreach(&index->entries, i, entry) {
1463
		if (GIT_IDXENTRY_STAGE(entry) > 0)
1464 1465 1466 1467 1468 1469
			return 1;
	}

	return 0;
}

1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 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 1523 1524 1525 1526 1527 1528 1529 1530 1531
int git_index_conflict_iterator_new(
	git_index_conflict_iterator **iterator_out,
	git_index *index)
{
	git_index_conflict_iterator *it = NULL;

	assert(iterator_out && index);

	it = git__calloc(1, sizeof(git_index_conflict_iterator));
	GITERR_CHECK_ALLOC(it);

	it->index = index;

	*iterator_out = it;
	return 0;
}

int git_index_conflict_next(
	const git_index_entry **ancestor_out,
	const git_index_entry **our_out,
	const git_index_entry **their_out,
	git_index_conflict_iterator *iterator)
{
	const git_index_entry *entry;
	int len;

	assert(ancestor_out && our_out && their_out && iterator);

	*ancestor_out = NULL;
	*our_out = NULL;
	*their_out = NULL;

	while (iterator->cur < iterator->index->entries.length) {
		entry = git_index_get_byindex(iterator->index, iterator->cur);

		if (git_index_entry_stage(entry) > 0) {
			if ((len = index_conflict__get_byindex(
				ancestor_out,
				our_out,
				their_out,
				iterator->index,
				iterator->cur)) < 0)
				return len;

			iterator->cur += len;
			return 0;
		}

		iterator->cur++;
	}

	return GIT_ITEROVER;
}

void git_index_conflict_iterator_free(git_index_conflict_iterator *iterator)
{
	if (iterator == NULL)
		return;

	git__free(iterator);
}

1532
size_t git_index_name_entrycount(git_index *index)
Edward Thomson committed
1533 1534
{
	assert(index);
1535
	return index->names.length;
Edward Thomson committed
1536 1537 1538 1539 1540 1541
}

const git_index_name_entry *git_index_name_get_byindex(
	git_index *index, size_t n)
{
	assert(index);
nulltoken committed
1542

Edward Thomson committed
1543 1544 1545 1546
	git_vector_sort(&index->names);
	return git_vector_get(&index->names, n);
}

1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
static void index_name_entry_free(git_index_name_entry *ne)
{
	if (!ne)
		return;
	git__free(ne->ancestor);
	git__free(ne->ours);
	git__free(ne->theirs);
	git__free(ne);
}

Edward Thomson committed
1557 1558 1559 1560 1561
int git_index_name_add(git_index *index,
	const char *ancestor, const char *ours, const char *theirs)
{
	git_index_name_entry *conflict_name;

1562
	assert((ancestor && ours) || (ancestor && theirs) || (ours && theirs));
Edward Thomson committed
1563 1564 1565

	conflict_name = git__calloc(1, sizeof(git_index_name_entry));
	GITERR_CHECK_ALLOC(conflict_name);
nulltoken committed
1566

1567 1568 1569 1570 1571 1572 1573
	if ((ancestor && !(conflict_name->ancestor = git__strdup(ancestor))) ||
		(ours     && !(conflict_name->ours     = git__strdup(ours))) ||
		(theirs   && !(conflict_name->theirs   = git__strdup(theirs))) ||
		git_vector_insert(&index->names, conflict_name) < 0)
	{
		index_name_entry_free(conflict_name);
		return -1;
Edward Thomson committed
1574
	}
nulltoken committed
1575

1576
	return 0;
Edward Thomson committed
1577 1578 1579 1580 1581 1582 1583 1584
}

void git_index_name_clear(git_index *index)
{
	size_t i;
	git_index_name_entry *conflict_name;

	assert(index);
nulltoken committed
1585

1586 1587
	git_vector_foreach(&index->names, i, conflict_name)
		index_name_entry_free(conflict_name);
nulltoken committed
1588

Edward Thomson committed
1589 1590 1591
	git_vector_clear(&index->names);
}

1592
size_t git_index_reuc_entrycount(git_index *index)
Edward Thomson committed
1593 1594
{
	assert(index);
1595
	return index->reuc.length;
Edward Thomson committed
1596 1597
}

Edward Thomson committed
1598 1599 1600 1601
static int index_reuc_insert(
	git_index *index,
	git_index_reuc_entry *reuc,
	int replace)
Edward Thomson committed
1602 1603
{
	git_index_reuc_entry **existing = NULL;
1604
	size_t position;
Edward Thomson committed
1605 1606 1607

	assert(index && reuc && reuc->path != NULL);

1608
	if (!git_index_reuc_find(&position, index, reuc->path))
Edward Thomson committed
1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621
		existing = (git_index_reuc_entry **)&index->reuc.contents[position];

	if (!replace || !existing)
		return git_vector_insert(&index->reuc, reuc);

	/* exists, replace it */
	git__free(*existing);
	*existing = reuc;

	return 0;
}

int git_index_reuc_add(git_index *index, const char *path,
Edward Thomson committed
1622 1623 1624
	int ancestor_mode, const git_oid *ancestor_oid,
	int our_mode, const git_oid *our_oid,
	int their_mode, const git_oid *their_oid)
Edward Thomson committed
1625 1626 1627 1628 1629 1630
{
	git_index_reuc_entry *reuc = NULL;
	int error = 0;

	assert(index && path);

1631 1632
	if ((error = index_entry_reuc_init(&reuc, path, ancestor_mode,
			ancestor_oid, our_mode, our_oid, their_mode, their_oid)) < 0 ||
Edward Thomson committed
1633 1634 1635 1636
		(error = index_reuc_insert(index, reuc, 1)) < 0)
		index_entry_reuc_free(reuc);

	return error;
1637
}
Edward Thomson committed
1638

1639
int git_index_reuc_find(size_t *at_pos, git_index *index, const char *path)
1640
{
1641
	return git_vector_bsearch2(at_pos, &index->reuc, index->reuc_search, path);
1642 1643
}

Edward Thomson committed
1644
const git_index_reuc_entry *git_index_reuc_get_bypath(
1645
	git_index *index, const char *path)
1646
{
1647
	size_t pos;
1648
	assert(index && path);
1649

Edward Thomson committed
1650
	if (!index->reuc.length)
1651
		return NULL;
1652

Edward Thomson committed
1653 1654
	git_vector_sort(&index->reuc);

1655
	if (git_index_reuc_find(&pos, index, path) < 0)
1656
		return NULL;
1657

Edward Thomson committed
1658
	return git_vector_get(&index->reuc, pos);
1659 1660
}

Edward Thomson committed
1661
const git_index_reuc_entry *git_index_reuc_get_byindex(
1662
	git_index *index, size_t n)
1663 1664
{
	assert(index);
Edward Thomson committed
1665 1666 1667 1668 1669

	git_vector_sort(&index->reuc);
	return git_vector_get(&index->reuc, n);
}

Ben Straub committed
1670
int git_index_reuc_remove(git_index *index, size_t position)
Edward Thomson committed
1671 1672 1673 1674 1675 1676 1677
{
	int error;
	git_index_reuc_entry *reuc;

	git_vector_sort(&index->reuc);

	reuc = git_vector_get(&index->reuc, position);
1678
	error = git_vector_remove(&index->reuc, position);
Edward Thomson committed
1679 1680 1681 1682 1683

	if (!error)
		index_entry_reuc_free(reuc);

	return error;
1684 1685
}

Edward Thomson committed
1686 1687 1688 1689 1690 1691
void git_index_reuc_clear(git_index *index)
{
	size_t i;

	assert(index);

1692 1693
	for (i = 0; i < index->reuc.length; ++i)
		index_entry_reuc_free(git__swap(index->reuc.contents[i], NULL));
Edward Thomson committed
1694 1695 1696 1697

	git_vector_clear(&index->reuc);
}

1698 1699 1700 1701 1702 1703
static int index_error_invalid(const char *message)
{
	giterr_set(GITERR_INDEX, "Invalid data in index - %s", message);
	return -1;
}

Edward Thomson committed
1704
static int read_reuc(git_index *index, const char *buffer, size_t size)
1705
{
1706 1707
	const char *endptr;
	size_t len;
1708 1709
	int i;

1710 1711 1712
	/* If called multiple times, the vector might already be initialized */
	if (index->reuc._alloc_size == 0 &&
		git_vector_init(&index->reuc, 16, reuc_cmp) < 0)
1713
		return -1;
1714 1715

	while (size) {
Edward Thomson committed
1716
		git_index_reuc_entry *lost;
1717

1718
		len = p_strnlen(buffer, size) + 1;
1719
		if (size <= len)
Edward Thomson committed
1720
			return index_error_invalid("reading reuc entries");
1721

1722
		lost = reuc_entry_alloc(buffer);
1723
		GITERR_CHECK_ALLOC(lost);
1724 1725 1726 1727

		size -= len;
		buffer += len;

1728
		/* read 3 ASCII octal numbers for stage entries */
1729
		for (i = 0; i < 3; i++) {
1730
			int tmp;
1731

1732 1733
			if (git__strtol32(&tmp, buffer, &endptr, 8) < 0 ||
				!endptr || endptr == buffer || *endptr ||
1734 1735
				(unsigned)tmp > UINT_MAX) {
				index_entry_reuc_free(lost);
Edward Thomson committed
1736
				return index_error_invalid("reading reuc entry stage");
1737
			}
1738

1739 1740
			lost->mode[i] = tmp;

1741
			len = (endptr + 1) - buffer;
1742 1743
			if (size <= len) {
				index_entry_reuc_free(lost);
Edward Thomson committed
1744
				return index_error_invalid("reading reuc entry stage");
1745
			}
1746

1747 1748 1749 1750
			size -= len;
			buffer += len;
		}

1751
		/* read up to 3 OIDs for stage entries */
1752 1753 1754
		for (i = 0; i < 3; i++) {
			if (!lost->mode[i])
				continue;
1755 1756
			if (size < 20) {
				index_entry_reuc_free(lost);
Edward Thomson committed
1757
				return index_error_invalid("reading reuc entry oid");
1758
			}
1759

1760
			git_oid_fromraw(&lost->oid[i], (const unsigned char *) buffer);
1761 1762 1763
			size -= 20;
			buffer += 20;
		}
1764 1765 1766 1767

		/* entry was read successfully - insert into reuc vector */
		if (git_vector_insert(&index->reuc, lost) < 0)
			return -1;
1768 1769
	}

Edward Thomson committed
1770
	/* entries are guaranteed to be sorted on-disk */
1771
	git_vector_set_sorted(&index->reuc, true);
Edward Thomson committed
1772

1773
	return 0;
1774 1775
}

Edward Thomson committed
1776 1777 1778 1779

static int read_conflict_names(git_index *index, const char *buffer, size_t size)
{
	size_t len;
nulltoken committed
1780

Edward Thomson committed
1781 1782 1783 1784 1785 1786
	/* This gets called multiple times, the vector might already be initialized */
	if (index->names._alloc_size == 0 &&
		git_vector_init(&index->names, 16, conflict_name_cmp) < 0)
		return -1;

#define read_conflict_name(ptr) \
1787
	len = p_strnlen(buffer, size) + 1; \
Edward Thomson committed
1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800
	if (size < len) \
		return index_error_invalid("reading conflict name entries"); \
	\
	if (len == 1) \
		ptr = NULL; \
	else { \
		ptr = git__malloc(len); \
		GITERR_CHECK_ALLOC(ptr); \
		memcpy(ptr, buffer, len); \
	} \
	\
	buffer += len; \
	size -= len;
nulltoken committed
1801

Edward Thomson committed
1802 1803 1804 1805 1806 1807 1808
	while (size) {
		git_index_name_entry *conflict_name = git__calloc(1, sizeof(git_index_name_entry));
		GITERR_CHECK_ALLOC(conflict_name);

		read_conflict_name(conflict_name->ancestor);
		read_conflict_name(conflict_name->ours);
		read_conflict_name(conflict_name->theirs);
nulltoken committed
1809

Edward Thomson committed
1810 1811 1812 1813 1814
		if (git_vector_insert(&index->names, conflict_name) < 0)
			return -1;
	}

#undef read_conflict_name
nulltoken committed
1815

Edward Thomson committed
1816
	/* entries are guaranteed to be sorted on-disk */
1817
	git_vector_set_sorted(&index->names, true);
nulltoken committed
1818 1819

	return 0;
Edward Thomson committed
1820 1821
}

1822
static size_t read_entry(
1823 1824 1825 1826
	git_index_entry **out,
	git_index *index,
	const void *buffer,
	size_t buffer_size)
1827 1828 1829
{
	size_t path_length, entry_size;
	const char *path_ptr;
1830
	struct entry_short source;
1831
	git_index_entry entry = {{0}};
1832 1833 1834 1835

	if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size)
		return 0;

1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850
	/* buffer is not guaranteed to be aligned */
	memcpy(&source, buffer, sizeof(struct entry_short));

	entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds);
	entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds);
	entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds);
	entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds);
	entry.dev = ntohl(source.dev);
	entry.ino = ntohl(source.ino);
	entry.mode = ntohl(source.mode);
	entry.uid = ntohl(source.uid);
	entry.gid = ntohl(source.gid);
	entry.file_size = ntohl(source.file_size);
	git_oid_cpy(&entry.id, &source.oid);
	entry.flags = ntohs(source.flags);
1851 1852

	if (entry.flags & GIT_IDXENTRY_EXTENDED) {
1853 1854
		uint16_t flags_raw;
		size_t flags_offset;
1855

1856 1857 1858 1859 1860 1861 1862
		flags_offset = offsetof(struct entry_long, flags_extended);
		memcpy(&flags_raw, (const char *) buffer + flags_offset,
			sizeof(flags_raw));
		flags_raw = ntohs(flags_raw);

		memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw));
		path_ptr = (const char *) buffer + offsetof(struct entry_long, path);
1863
	} else
1864
		path_ptr = (const char *) buffer + offsetof(struct entry_short, path);
1865

1866
	path_length = entry.flags & GIT_IDXENTRY_NAMEMASK;
1867 1868 1869 1870 1871 1872 1873 1874

	/* if this is a very long string, we must find its
	 * real length without overflowing */
	if (path_length == 0xFFF) {
		const char *path_end;

		path_end = memchr(path_ptr, '\0', buffer_size);
		if (path_end == NULL)
1875
			return 0;
1876 1877 1878 1879

		path_length = path_end - path_ptr;
	}

1880
	if (entry.flags & GIT_IDXENTRY_EXTENDED)
1881 1882 1883 1884 1885 1886 1887
		entry_size = long_entry_size(path_length);
	else
		entry_size = short_entry_size(path_length);

	if (INDEX_FOOTER_SIZE + entry_size > buffer_size)
		return 0;

1888 1889
	entry.path = (char *)path_ptr;

1890
	if (index_entry_dup(out, INDEX_OWNER(index), &entry) < 0)
1891
		return 0;
1892 1893 1894 1895 1896 1897

	return entry_size;
}

static int read_header(struct index_header *dest, const void *buffer)
{
1898
	const struct index_header *source = buffer;
1899

1900 1901
	dest->signature = ntohl(source->signature);
	if (dest->signature != INDEX_HEADER_SIG)
1902
		return index_error_invalid("incorrect header signature");
1903 1904

	dest->version = ntohl(source->version);
1905 1906
	if (dest->version != INDEX_VERSION_NUMBER_EXT &&
		dest->version != INDEX_VERSION_NUMBER)
1907
		return index_error_invalid("incorrect header version");
1908 1909

	dest->entry_count = ntohl(source->entry_count);
1910
	return 0;
1911 1912 1913 1914 1915 1916 1917
}

static size_t read_extension(git_index *index, const char *buffer, size_t buffer_size)
{
	struct index_extension dest;
	size_t total_size;

1918 1919 1920
	/* buffer is not guaranteed to be aligned */
	memcpy(&dest, buffer, sizeof(struct index_extension));
	dest.extension_size = ntohl(dest.extension_size);
1921 1922 1923

	total_size = dest.extension_size + sizeof(struct index_extension);

1924 1925
	if (dest.extension_size > total_size ||
		buffer_size < total_size ||
1926
		buffer_size - total_size < INDEX_FOOTER_SIZE)
1927 1928 1929 1930 1931 1932
		return 0;

	/* optional extension */
	if (dest.signature[0] >= 'A' && dest.signature[0] <= 'Z') {
		/* tree cache */
		if (memcmp(dest.signature, INDEX_EXT_TREECACHE_SIG, 4) == 0) {
1933
			if (git_tree_cache_read(&index->tree, buffer + 8, dest.extension_size, &index->tree_pool) < 0)
1934
				return 0;
1935
		} else if (memcmp(dest.signature, INDEX_EXT_UNMERGED_SIG, 4) == 0) {
Edward Thomson committed
1936
			if (read_reuc(index, buffer + 8, dest.extension_size) < 0)
1937
				return 0;
Edward Thomson committed
1938 1939 1940
		} else if (memcmp(dest.signature, INDEX_EXT_CONFLICT_NAME_SIG, 4) == 0) {
			if (read_conflict_names(index, buffer + 8, dest.extension_size) < 0)
				return 0;
1941
		}
1942 1943
		/* else, unsupported extension. We cannot parse this, but we can skip
		 * it by returning `total_size */
1944 1945 1946 1947 1948 1949 1950 1951 1952
	} else {
		/* we cannot handle non-ignorable extensions;
		 * in fact they aren't even defined in the standard */
		return 0;
	}

	return total_size;
}

1953
static int parse_index(git_index *index, const char *buffer, size_t buffer_size)
1954
{
1955
	int error = 0;
1956
	unsigned int i;
1957
	struct index_header header = { 0 };
1958 1959 1960
	git_oid checksum_calculated, checksum_expected;

#define seek_forward(_increase) { \
1961 1962 1963
	if (_increase >= buffer_size) { \
		error = index_error_invalid("ran out of data while parsing"); \
		goto done; } \
1964 1965 1966 1967 1968
	buffer += _increase; \
	buffer_size -= _increase;\
}

	if (buffer_size < INDEX_HEADER_SIZE + INDEX_FOOTER_SIZE)
1969
		return index_error_invalid("insufficient buffer space");
1970 1971 1972

	/* Precalculate the SHA1 of the files's contents -- we'll match it to
	 * the provided SHA1 in the footer */
1973
	git_hash_buf(&checksum_calculated, buffer, buffer_size - INDEX_FOOTER_SIZE);
1974 1975

	/* Parse header */
1976 1977
	if ((error = read_header(&header, buffer)) < 0)
		return error;
1978 1979 1980

	seek_forward(INDEX_HEADER_SIZE);

1981 1982 1983 1984 1985
	if (git_mutex_lock(&index->lock) < 0) {
		giterr_set(GITERR_OS, "Unable to acquire index lock");
		return -1;
	}

1986
	assert(!index->entries.length);
1987 1988

	/* Parse all the entries */
1989 1990
	for (i = 0; i < header.entry_count && buffer_size > INDEX_FOOTER_SIZE; ++i) {
		git_index_entry *entry;
1991
		size_t entry_size = read_entry(&entry, index, buffer, buffer_size);
1992 1993

		/* 0 bytes read means an object corruption */
1994 1995 1996 1997
		if (entry_size == 0) {
			error = index_error_invalid("invalid entry");
			goto done;
		}
1998

1999 2000
		if ((error = git_vector_insert(&index->entries, entry)) < 0) {
			index_entry_free(entry);
2001
			goto done;
2002
		}
2003

2004 2005 2006
		seek_forward(entry_size);
	}

2007 2008 2009 2010
	if (i != header.entry_count) {
		error = index_error_invalid("header entries changed while parsing");
		goto done;
	}
2011

2012 2013 2014 2015 2016 2017 2018
	/* There's still space for some extensions! */
	while (buffer_size > INDEX_FOOTER_SIZE) {
		size_t extension_size;

		extension_size = read_extension(index, buffer, buffer_size);

		/* see if we have read any bytes from the extension */
2019 2020 2021 2022
		if (extension_size == 0) {
			error = index_error_invalid("extension is truncated");
			goto done;
		}
2023 2024 2025 2026

		seek_forward(extension_size);
	}

2027 2028 2029 2030 2031
	if (buffer_size != INDEX_FOOTER_SIZE) {
		error = index_error_invalid(
			"buffer size does not match index footer size");
		goto done;
	}
2032 2033

	/* 160-bit SHA-1 over the content of the index file before this checksum. */
Vicent Marti committed
2034
	git_oid_fromraw(&checksum_expected, (const unsigned char *)buffer);
2035

2036 2037 2038 2039 2040
	if (git_oid__cmp(&checksum_calculated, &checksum_expected) != 0) {
		error = index_error_invalid(
			"calculated checksum does not match expected");
		goto done;
	}
2041 2042 2043

#undef seek_forward

2044 2045 2046 2047
	/* Entries are stored case-sensitively on disk, so re-sort now if
	 * in-memory index is supposed to be case-insensitive
	 */
	git_vector_set_sorted(&index->entries, !index->ignore_case);
2048
	error = index_sort_if_needed(index, false);
2049

2050
done:
2051
	git_mutex_unlock(&index->lock);
2052
	return error;
2053 2054
}

2055
static bool is_index_extended(git_index *index)
Vicent Marti committed
2056
{
2057
	size_t i, extended;
2058
	git_index_entry *entry;
Vicent Marti committed
2059 2060 2061

	extended = 0;

2062
	git_vector_foreach(&index->entries, i, entry) {
Vicent Marti committed
2063 2064 2065 2066 2067 2068
		entry->flags &= ~GIT_IDXENTRY_EXTENDED;
		if (entry->flags_extended & GIT_IDXENTRY_EXTENDED_FLAGS) {
			extended++;
			entry->flags |= GIT_IDXENTRY_EXTENDED;
		}
	}
2069

2070
	return (extended > 0);
Vicent Marti committed
2071 2072
}

2073
static int write_disk_entry(git_filebuf *file, git_index_entry *entry)
2074
{
2075
	void *mem = NULL;
2076
	struct entry_short *ondisk;
2077
	size_t path_len, disk_size;
2078
	char *path;
2079

2080
	path_len = ((struct entry_internal *)entry)->pathlen;
2081

2082
	if (entry->flags & GIT_IDXENTRY_EXTENDED)
2083
		disk_size = long_entry_size(path_len);
2084
	else
2085
		disk_size = short_entry_size(path_len);
2086

2087 2088
	if (git_filebuf_reserve(file, &mem, disk_size) < 0)
		return -1;
2089

2090 2091
	ondisk = (struct entry_short *)mem;

2092
	memset(ondisk, 0x0, disk_size);
2093

2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105
	/**
	 * Yes, we have to truncate.
	 *
	 * The on-disk format for Index entries clearly defines
	 * the time and size fields to be 4 bytes each -- so even if
	 * we store these values with 8 bytes on-memory, they must
	 * be truncated to 4 bytes before writing to disk.
	 *
	 * In 2038 I will be either too dead or too rich to care about this
	 */
	ondisk->ctime.seconds = htonl((uint32_t)entry->ctime.seconds);
	ondisk->mtime.seconds = htonl((uint32_t)entry->mtime.seconds);
2106 2107
	ondisk->ctime.nanoseconds = htonl(entry->ctime.nanoseconds);
	ondisk->mtime.nanoseconds = htonl(entry->mtime.nanoseconds);
Vicent Marti committed
2108 2109
	ondisk->dev = htonl(entry->dev);
	ondisk->ino = htonl(entry->ino);
2110
	ondisk->mode = htonl(entry->mode);
Vicent Marti committed
2111 2112
	ondisk->uid = htonl(entry->uid);
	ondisk->gid = htonl(entry->gid);
2113
	ondisk->file_size = htonl((uint32_t)entry->file_size);
2114

2115
	git_oid_cpy(&ondisk->oid, &entry->id);
2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128

	ondisk->flags = htons(entry->flags);

	if (entry->flags & GIT_IDXENTRY_EXTENDED) {
		struct entry_long *ondisk_ext;
		ondisk_ext = (struct entry_long *)ondisk;
		ondisk_ext->flags_extended = htons(entry->flags_extended);
		path = ondisk_ext->path;
	}
	else
		path = ondisk->path;

	memcpy(path, entry->path, path_len);
2129

2130
	return 0;
2131 2132
}

2133
static int write_entries(git_index *index, git_filebuf *file)
2134
{
2135
	int error = 0;
2136
	size_t i;
2137
	git_vector case_sorted, *entries;
2138 2139
	git_index_entry *entry;

2140 2141 2142 2143 2144
	if (git_mutex_lock(&index->lock) < 0) {
		giterr_set(GITERR_OS, "Failed to lock index");
		return -1;
	}

2145 2146 2147
	/* If index->entries is sorted case-insensitively, then we need
	 * to re-sort it case-sensitively before writing */
	if (index->ignore_case) {
2148
		git_vector_dup(&case_sorted, &index->entries, git_index_entry_cmp);
2149
		git_vector_sort(&case_sorted);
2150 2151 2152
		entries = &case_sorted;
	} else {
		entries = &index->entries;
2153 2154
	}

2155
	git_vector_foreach(entries, i, entry)
2156 2157 2158
		if ((error = write_disk_entry(file, entry)) < 0)
			break;

2159 2160
	git_mutex_unlock(&index->lock);

2161 2162 2163 2164
	if (index->ignore_case)
		git_vector_free(&case_sorted);

	return error;
2165 2166
}

Edward Thomson committed
2167 2168 2169 2170 2171 2172 2173 2174
static int write_extension(git_filebuf *file, struct index_extension *header, git_buf *data)
{
	struct index_extension ondisk;

	memset(&ondisk, 0x0, sizeof(struct index_extension));
	memcpy(&ondisk, header, 4);
	ondisk.extension_size = htonl(header->extension_size);

2175 2176
	git_filebuf_write(file, &ondisk, sizeof(struct index_extension));
	return git_filebuf_write(file, data->ptr, data->size);
Edward Thomson committed
2177 2178
}

Edward Thomson committed
2179 2180 2181 2182 2183 2184 2185 2186
static int create_name_extension_data(git_buf *name_buf, git_index_name_entry *conflict_name)
{
	int error = 0;

	if (conflict_name->ancestor == NULL)
		error = git_buf_put(name_buf, "\0", 1);
	else
		error = git_buf_put(name_buf, conflict_name->ancestor, strlen(conflict_name->ancestor) + 1);
nulltoken committed
2187

Edward Thomson committed
2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215
	if (error != 0)
		goto on_error;

	if (conflict_name->ours == NULL)
		error = git_buf_put(name_buf, "\0", 1);
	else
		error = git_buf_put(name_buf, conflict_name->ours, strlen(conflict_name->ours) + 1);

	if (error != 0)
		goto on_error;

	if (conflict_name->theirs == NULL)
		error = git_buf_put(name_buf, "\0", 1);
	else
		error = git_buf_put(name_buf, conflict_name->theirs, strlen(conflict_name->theirs) + 1);

on_error:
	return error;
}

static int write_name_extension(git_index *index, git_filebuf *file)
{
	git_buf name_buf = GIT_BUF_INIT;
	git_vector *out = &index->names;
	git_index_name_entry *conflict_name;
	struct index_extension extension;
	size_t i;
	int error = 0;
nulltoken committed
2216

Edward Thomson committed
2217 2218 2219 2220
	git_vector_foreach(out, i, conflict_name) {
		if ((error = create_name_extension_data(&name_buf, conflict_name)) < 0)
			goto done;
	}
nulltoken committed
2221

Edward Thomson committed
2222 2223 2224
	memset(&extension, 0x0, sizeof(struct index_extension));
	memcpy(&extension.signature, INDEX_EXT_CONFLICT_NAME_SIG, 4);
	extension.extension_size = (uint32_t)name_buf.size;
nulltoken committed
2225

Edward Thomson committed
2226
	error = write_extension(file, &extension, &name_buf);
nulltoken committed
2227

Edward Thomson committed
2228
	git_buf_free(&name_buf);
nulltoken committed
2229

Edward Thomson committed
2230 2231 2232 2233
done:
	return error;
}

Edward Thomson committed
2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261
static int create_reuc_extension_data(git_buf *reuc_buf, git_index_reuc_entry *reuc)
{
	int i;
	int error = 0;

	if ((error = git_buf_put(reuc_buf, reuc->path, strlen(reuc->path) + 1)) < 0)
		return error;

	for (i = 0; i < 3; i++) {
		if ((error = git_buf_printf(reuc_buf, "%o", reuc->mode[i])) < 0 ||
			(error = git_buf_put(reuc_buf, "\0", 1)) < 0)
			return error;
	}

	for (i = 0; i < 3; i++) {
		if (reuc->mode[i] && (error = git_buf_put(reuc_buf, (char *)&reuc->oid[i].id, GIT_OID_RAWSZ)) < 0)
			return error;
	}

	return 0;
}

static int write_reuc_extension(git_index *index, git_filebuf *file)
{
	git_buf reuc_buf = GIT_BUF_INIT;
	git_vector *out = &index->reuc;
	git_index_reuc_entry *reuc;
	struct index_extension extension;
2262
	size_t i;
Edward Thomson committed
2263 2264 2265 2266 2267 2268 2269 2270 2271
	int error = 0;

	git_vector_foreach(out, i, reuc) {
		if ((error = create_reuc_extension_data(&reuc_buf, reuc)) < 0)
			goto done;
	}

	memset(&extension, 0x0, sizeof(struct index_extension));
	memcpy(&extension.signature, INDEX_EXT_UNMERGED_SIG, 4);
2272
	extension.extension_size = (uint32_t)reuc_buf.size;
Edward Thomson committed
2273 2274 2275 2276 2277 2278 2279 2280 2281

	error = write_extension(file, &extension, &reuc_buf);

	git_buf_free(&reuc_buf);

done:
	return error;
}

2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304
static int write_tree_extension(git_index *index, git_filebuf *file)
{
	struct index_extension extension;
	git_buf buf = GIT_BUF_INIT;
	int error;

	if (index->tree == NULL)
		return 0;

	if ((error = git_tree_cache_write(&buf, index->tree)) < 0)
		return error;

	memset(&extension, 0x0, sizeof(struct index_extension));
	memcpy(&extension.signature, INDEX_EXT_TREECACHE_SIG, 4);
	extension.extension_size = (uint32_t)buf.size;

	error = write_extension(file, &extension, &buf);

	git_buf_free(&buf);

	return error;
}

2305
static int write_index(git_index *index, git_filebuf *file)
2306 2307 2308
{
	git_oid hash_final;
	struct index_header header;
2309
	bool is_extended;
Ben Straub committed
2310
	uint32_t index_version_number;
2311

2312
	assert(index && file);
2313

Vicent Marti committed
2314
	is_extended = is_index_extended(index);
Ben Straub committed
2315
	index_version_number = is_extended ? INDEX_VERSION_NUMBER_EXT : INDEX_VERSION_NUMBER;
Vicent Marti committed
2316

2317
	header.signature = htonl(INDEX_HEADER_SIG);
Ben Straub committed
2318
	header.version = htonl(index_version_number);
2319
	header.entry_count = htonl((uint32_t)index->entries.length);
2320

2321 2322
	if (git_filebuf_write(file, &header, sizeof(struct index_header)) < 0)
		return -1;
2323

2324 2325
	if (write_entries(index, file) < 0)
		return -1;
2326

2327 2328 2329
	/* write the tree cache extension */
	if (index->tree != NULL && write_tree_extension(index, file) < 0)
		return -1;
Edward Thomson committed
2330

Edward Thomson committed
2331 2332 2333
	/* write the rename conflict extension */
	if (index->names.length > 0 && write_name_extension(index, file) < 0)
		return -1;
nulltoken committed
2334

Edward Thomson committed
2335 2336 2337
	/* write the reuc extension */
	if (index->reuc.length > 0 && write_reuc_extension(index, file) < 0)
		return -1;
2338

2339 2340 2341 2342
	/* get out the hash for all the contents we've appended to the file */
	git_filebuf_hash(&hash_final, file);

	/* write it at the end of the file */
2343
	return git_filebuf_write(file, hash_final.id, GIT_OID_RAWSZ);
2344
}
2345 2346 2347

int git_index_entry_stage(const git_index_entry *entry)
{
2348
	return GIT_IDXENTRY_STAGE(entry);
2349
}
2350

2351
typedef struct read_tree_data {
2352
	git_index *index;
2353
	git_vector *old_entries;
2354
	git_vector *new_entries;
2355
	git_vector_cmp entry_cmp;
2356
	git_tree_cache *tree;
2357 2358
} read_tree_data;

2359 2360
static int read_tree_cb(
	const char *root, const git_tree_entry *tentry, void *payload)
2361
{
2362 2363
	read_tree_data *data = payload;
	git_index_entry *entry = NULL, *old_entry;
2364
	git_buf path = GIT_BUF_INIT;
2365
	size_t pos;
2366

Vicent Martí committed
2367
	if (git_tree_entry__is_tree(tentry))
2368
		return 0;
2369

2370 2371
	if (git_buf_joinpath(&path, root, tentry->filename) < 0)
		return -1;
2372

2373
	if (index_entry_create(&entry, INDEX_OWNER(data->index), path.ptr) < 0)
2374
		return -1;
2375 2376

	entry->mode = tentry->attr;
2377
	entry->id = tentry->oid;
2378

2379
	/* look for corresponding old entry and copy data to new entry */
2380
	if (data->old_entries != NULL &&
2381
		!index_find_in_entries(
2382 2383 2384 2385 2386
			&pos, data->old_entries, data->entry_cmp, path.ptr, 0, 0) &&
		(old_entry = git_vector_get(data->old_entries, pos)) != NULL &&
		entry->mode == old_entry->mode &&
		git_oid_equal(&entry->id, &old_entry->id))
	{
2387
		index_entry_cpy(entry, old_entry);
2388
		entry->flags_extended = 0;
2389 2390
	}

2391 2392 2393 2394 2395
	if (path.size < GIT_IDXENTRY_NAMEMASK)
		entry->flags = path.size & GIT_IDXENTRY_NAMEMASK;
	else
		entry->flags = GIT_IDXENTRY_NAMEMASK;

2396 2397
	git_buf_free(&path);

2398
	if (git_vector_insert(data->new_entries, entry) < 0) {
2399
		index_entry_free(entry);
2400 2401 2402 2403
		return -1;
	}

	return 0;
2404 2405
}

Ben Straub committed
2406
int git_index_read_tree(git_index *index, const git_tree *tree)
2407
{
2408 2409 2410 2411
	int error = 0;
	git_vector entries = GIT_VECTOR_INIT;
	read_tree_data data;

2412
	git_vector_set_cmp(&entries, index->entries._cmp); /* match sort */
2413

2414
	data.index = index;
2415 2416
	data.old_entries = &index->entries;
	data.new_entries = &entries;
2417
	data.entry_cmp   = index->entries_search;
2418

2419 2420 2421
	index->tree = NULL;
	git_pool_clear(&index->tree_pool);

2422 2423
	if (index_sort_if_needed(index, true) < 0)
		return -1;
2424 2425 2426

	error = git_tree_walk(tree, GIT_TREEWALK_POST, read_tree_cb, &data);

2427 2428
	if (!error) {
		git_vector_sort(&entries);
2429 2430 2431

		if ((error = git_index_clear(index)) < 0)
			/* well, this isn't good */;
2432 2433 2434 2435
		else if (git_mutex_lock(&index->lock) < 0) {
			giterr_set(GITERR_OS, "Unable to acquire index lock");
			error = -1;
		} else {
2436
			git_vector_swap(&entries, &index->entries);
2437 2438
			git_mutex_unlock(&index->lock);
		}
2439 2440
	}

2441
	git_vector_free(&entries);
2442 2443 2444 2445
	if (error < 0)
		return error;

	error = git_tree_cache_read_tree(&index->tree, tree, &index->tree_pool);
2446 2447

	return error;
2448
}
2449 2450 2451 2452 2453

git_repository *git_index_owner(const git_index *index)
{
	return INDEX_OWNER(index);
}
2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466

int git_index_add_all(
	git_index *index,
	const git_strarray *paths,
	unsigned int flags,
	git_index_matched_path_cb cb,
	void *payload)
{
	int error;
	git_repository *repo;
	git_iterator *wditer = NULL;
	const git_index_entry *wd = NULL;
	git_index_entry *entry;
2467
	git_pathspec ps;
2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487
	const char *match;
	size_t existing;
	bool no_fnmatch = (flags & GIT_INDEX_ADD_DISABLE_PATHSPEC_MATCH) != 0;
	int ignorecase;
	git_oid blobid;

	assert(index);

	if (INDEX_OWNER(index) == NULL)
		return create_index_error(-1,
			"Could not add paths to index. "
			"Index is not backed up by an existing repository.");

	repo = INDEX_OWNER(index);
	if ((error = git_repository__ensure_not_bare(repo, "index add all")) < 0)
		return error;

	if (git_repository__cvar(&ignorecase, repo, GIT_CVAR_IGNORECASE) < 0)
		return -1;

2488
	if ((error = git_pathspec__init(&ps, paths)) < 0)
2489 2490 2491 2492 2493 2494 2495 2496 2497 2498
		return error;

	/* optionally check that pathspec doesn't mention any ignored files */
	if ((flags & GIT_INDEX_ADD_CHECK_PATHSPEC) != 0 &&
		(flags & GIT_INDEX_ADD_FORCE) == 0 &&
		(error = git_ignore__check_pathspec_for_exact_ignores(
			repo, &ps.pathspec, no_fnmatch)) < 0)
		goto cleanup;

	if ((error = git_iterator_for_workdir(
2499
			&wditer, repo, NULL, NULL, 0, ps.prefix, ps.prefix)) < 0)
2500 2501 2502 2503 2504
		goto cleanup;

	while (!(error = git_iterator_advance(&wd, wditer))) {

		/* check if path actually matches */
2505
		if (!git_pathspec__match(
Linquize committed
2506
				&ps.pathspec, wd->path, no_fnmatch, (bool)ignorecase, &match, NULL))
2507 2508 2509 2510 2511
			continue;

		/* skip ignored items that are not already in the index */
		if ((flags & GIT_INDEX_ADD_FORCE) == 0 &&
			git_iterator_current_is_ignored(wditer) &&
2512
			index_find(&existing, index, wd->path, 0, 0, true) < 0)
2513 2514 2515 2516 2517 2518 2519
			continue;

		/* issue notification callback if requested */
		if (cb && (error = cb(wd->path, match, payload)) != 0) {
			if (error > 0) /* return > 0 means skip this one */
				continue;
			if (error < 0) { /* return < 0 means abort */
2520
				giterr_set_after_callback(error);
2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533
				break;
			}
		}

		/* TODO: Should we check if the file on disk is already an exact
		 * match to the file in the index and skip this work if it is?
		 */

		/* write the blob to disk and get the oid */
		if ((error = git_blob_create_fromworkdir(&blobid, repo, wd->path)) < 0)
			break;

		/* make the new entry to insert */
2534
		if ((error = index_entry_dup(&entry, INDEX_OWNER(index), wd)) < 0)
2535
			break;
2536

2537
		entry->id = blobid;
2538 2539

		/* add working directory item to index */
2540
		if ((error = index_insert(index, &entry, 1)) < 0)
2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557
			break;

		git_tree_cache_invalidate_path(index->tree, wd->path);

		/* add implies conflict resolved, move conflict entries to REUC */
		if ((error = index_conflict_to_reuc(index, wd->path)) < 0) {
			if (error != GIT_ENOTFOUND)
				break;
			giterr_clear();
		}
	}

	if (error == GIT_ITEROVER)
		error = 0;

cleanup:
	git_iterator_free(wditer);
2558
	git_pathspec__clear(&ps);
2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577

	return error;
}

enum {
	INDEX_ACTION_NONE = 0,
	INDEX_ACTION_UPDATE = 1,
	INDEX_ACTION_REMOVE = 2,
};

static int index_apply_to_all(
	git_index *index,
	int action,
	const git_strarray *paths,
	git_index_matched_path_cb cb,
	void *payload)
{
	int error = 0;
	size_t i;
2578
	git_pathspec ps;
2579
	const char *match;
2580
	git_buf path = GIT_BUF_INIT;
2581 2582 2583

	assert(index);

2584
	if ((error = git_pathspec__init(&ps, paths)) < 0)
2585 2586 2587 2588 2589 2590 2591 2592
		return error;

	git_vector_sort(&index->entries);

	for (i = 0; !error && i < index->entries.length; ++i) {
		git_index_entry *entry = git_vector_get(&index->entries, i);

		/* check if path actually matches */
2593
		if (!git_pathspec__match(
Linquize committed
2594
				&ps.pathspec, entry->path, false, (bool)index->ignore_case,
2595
				&match, NULL))
2596 2597 2598 2599 2600 2601 2602 2603
			continue;

		/* issue notification callback if requested */
		if (cb && (error = cb(entry->path, match, payload)) != 0) {
			if (error > 0) { /* return > 0 means skip this one */
				error = 0;
				continue;
			}
2604
			if (error < 0)   /* return < 0 means abort */
2605 2606 2607
				break;
		}

2608 2609 2610 2611
		/* index manipulation may alter entry, so don't depend on it */
		if ((error = git_buf_sets(&path, entry->path)) < 0)
			break;

2612 2613 2614 2615
		switch (action) {
		case INDEX_ACTION_NONE:
			break;
		case INDEX_ACTION_UPDATE:
2616
			error = git_index_add_bypath(index, path.ptr);
2617 2618 2619 2620

			if (error == GIT_ENOTFOUND) {
				giterr_clear();

2621
				error = git_index_remove_bypath(index, path.ptr);
2622 2623 2624 2625 2626 2627

				if (!error) /* back up foreach if we removed this */
					i--;
			}
			break;
		case INDEX_ACTION_REMOVE:
2628
			if (!(error = git_index_remove_bypath(index, path.ptr)))
2629 2630 2631 2632 2633 2634 2635 2636 2637
				i--; /* back up foreach if we removed this */
			break;
		default:
			giterr_set(GITERR_INVALID, "Unknown index action %d", action);
			error = -1;
			break;
		}
	}

2638
	git_buf_free(&path);
2639
	git_pathspec__clear(&ps);
2640 2641 2642 2643 2644 2645 2646 2647 2648 2649

	return error;
}

int git_index_remove_all(
	git_index *index,
	const git_strarray *pathspec,
	git_index_matched_path_cb cb,
	void *payload)
{
2650
	int error = index_apply_to_all(
2651
		index, INDEX_ACTION_REMOVE, pathspec, cb, payload);
2652 2653 2654 2655 2656

	if (error) /* make sure error is set if callback stopped iteration */
		giterr_set_after_callback(error);

	return error;
2657 2658 2659 2660 2661 2662 2663 2664
}

int git_index_update_all(
	git_index *index,
	const git_strarray *pathspec,
	git_index_matched_path_cb cb,
	void *payload)
{
2665
	int error = index_apply_to_all(
2666
		index, INDEX_ACTION_UPDATE, pathspec, cb, payload);
2667 2668 2669 2670 2671

	if (error) /* make sure error is set if callback stopped iteration */
		giterr_set_after_callback(error);

	return error;
2672
}
2673

2674
int git_index_snapshot_new(git_vector *snap, git_index *index)
2675 2676 2677 2678
{
	int error;

	GIT_REFCOUNT_INC(index);
2679 2680 2681 2682 2683 2684 2685

	if (git_mutex_lock(&index->lock) < 0) {
		giterr_set(GITERR_OS, "Failed to lock index");
		return -1;
	}

	git_atomic_inc(&index->readers);
2686
	git_vector_sort(&index->entries);
2687

2688
	error = git_vector_dup(snap, &index->entries, index->entries._cmp);
2689

2690 2691
	git_mutex_unlock(&index->lock);

2692 2693 2694 2695 2696 2697
	if (error < 0)
		git_index_free(index);

	return error;
}

2698
void git_index_snapshot_release(git_vector *snap, git_index *index)
2699
{
2700 2701
	git_vector_free(snap);

2702 2703 2704 2705 2706 2707
	git_atomic_dec(&index->readers);

	if (!git_mutex_lock(&index->lock)) {
		index_free_deleted(index); /* try to free pending deleted items */
		git_mutex_unlock(&index->lock);
	}
2708 2709

	git_index_free(index);
2710
}
2711 2712 2713 2714 2715 2716 2717

int git_index_snapshot_find(
	size_t *out, git_vector *entries, git_vector_cmp entry_srch,
	const char *path, size_t path_len, int stage)
{
	return index_find_in_entries(out, entries, entry_srch, path, path_len, stage);
}
2718 2719 2720 2721 2722 2723 2724

int git_indexwriter_init(
	git_indexwriter *writer,
	git_index *index)
{
	int error;

2725 2726
	GIT_REFCOUNT_INC(index);

2727 2728 2729 2730 2731 2732 2733 2734
	writer->index = index;

	if (!index->index_file_path)
		return create_index_error(-1,
			"Failed to write index: The index is in-memory only");

	if ((error = git_filebuf_open(
		&writer->file, index->index_file_path, GIT_FILEBUF_HASH_CONTENTS, GIT_INDEX_FILE_MODE)) < 0) {
2735

2736 2737 2738 2739 2740 2741
		if (error == GIT_ELOCKED)
			giterr_set(GITERR_INDEX, "The index is locked. This might be due to a concurrent or crashed process");

		return error;
	}

2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761
	writer->should_write = 1;

	return 0;
}

int git_indexwriter_init_for_operation(
	git_indexwriter *writer,
	git_repository *repo,
	unsigned int *checkout_strategy)
{
	git_index *index;
	int error;

	if ((error = git_repository_index__weakptr(&index, repo)) < 0 ||
		(error = git_indexwriter_init(writer, index)) < 0)
		return error;

	writer->should_write = (*checkout_strategy & GIT_CHECKOUT_DONT_WRITE_INDEX) == 0;
	*checkout_strategy |= GIT_CHECKOUT_DONT_WRITE_INDEX;

2762 2763 2764 2765 2766 2767 2768
	return 0;
}

int git_indexwriter_commit(git_indexwriter *writer)
{
	int error;

2769 2770 2771
	if (!writer->should_write)
		return 0;

2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792
	if (index_sort_if_needed(writer->index, true) < 0)
		return -1;

	git_vector_sort(&writer->index->reuc);

	if ((error = write_index(writer->index, &writer->file)) < 0) {
		git_indexwriter_cleanup(writer);
		return error;
	}

	if ((error = git_filebuf_commit(&writer->file)) < 0)
		return error;

	if ((error = git_futils_filestamp_check(
		&writer->index->stamp, writer->index->index_file_path)) < 0) {
		giterr_set(GITERR_OS, "Could not read index timestamp");
		return -1;
	}

	writer->index->on_disk = 1;

2793 2794 2795
	git_index_free(writer->index);
	writer->index = NULL;

2796 2797 2798 2799 2800 2801
	return 0;
}

void git_indexwriter_cleanup(git_indexwriter *writer)
{
	git_filebuf_cleanup(&writer->file);
2802 2803 2804

	git_index_free(writer->index);
	writer->index = NULL;
2805
}