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

8 9
#include "checkout.h"

10 11 12
#include "git2/repository.h"
#include "git2/refs.h"
#include "git2/tree.h"
13
#include "git2/blob.h"
14
#include "git2/config.h"
15
#include "git2/diff.h"
16
#include "git2/submodule.h"
Vicent Marti committed
17
#include "git2/sys/index.h"
18
#include "git2/sys/filter.h"
19
#include "git2/merge.h"
20 21

#include "refs.h"
22
#include "repository.h"
23
#include "index.h"
Ben Straub committed
24
#include "filter.h"
Ben Straub committed
25
#include "blob.h"
26
#include "diff.h"
27
#include "diff_generate.h"
28
#include "pathspec.h"
29
#include "buf_text.h"
30
#include "diff_xdiff.h"
31
#include "path.h"
32
#include "attr.h"
33 34 35
#include "pool.h"
#include "strmap.h"

36
/* See docs/checkout-internals.md for more information */
37

38 39 40 41 42 43
enum {
	CHECKOUT_ACTION__NONE = 0,
	CHECKOUT_ACTION__REMOVE = 1,
	CHECKOUT_ACTION__UPDATE_BLOB = 2,
	CHECKOUT_ACTION__UPDATE_SUBMODULE = 4,
	CHECKOUT_ACTION__CONFLICT = 8,
44 45 46
	CHECKOUT_ACTION__REMOVE_CONFLICT = 16,
	CHECKOUT_ACTION__UPDATE_CONFLICT = 32,
	CHECKOUT_ACTION__MAX = 32,
47 48 49 50 51 52
	CHECKOUT_ACTION__REMOVE_AND_UPDATE =
		(CHECKOUT_ACTION__UPDATE_BLOB | CHECKOUT_ACTION__REMOVE),
};

typedef struct {
	git_repository *repo;
53
	git_iterator *target;
54
	git_diff *diff;
55
	git_checkout_options opts;
56 57 58 59 60
	bool opts_free_baseline;
	char *pfx;
	git_index *index;
	git_pool pool;
	git_vector removes;
61 62 63 64
	git_vector remove_conflicts;
	git_vector update_conflicts;
	git_vector *update_reuc;
	git_vector *update_names;
65 66
	git_buf target_path;
	size_t target_len;
67
	git_buf tmp;
68 69
	unsigned int strategy;
	int can_symlink;
70
	int respect_filemode;
71 72 73
	bool reload_submodules;
	size_t total_steps;
	size_t completed_steps;
74
	git_checkout_perfdata perfdata;
75
	git_strmap *mkdir_map;
76
	git_attr_session attr_session;
77 78 79 80 81 82 83 84 85
} checkout_data;

typedef struct {
	const git_index_entry *ancestor;
	const git_index_entry *ours;
	const git_index_entry *theirs;

	int name_collision:1,
		directoryfile:1,
86
		one_to_two:1,
Edward Thomson committed
87 88
		binary:1,
		submodule:1;
89 90
} checkout_conflictdata;

91
static int checkout_notify(
92
	checkout_data *data,
93 94
	git_checkout_notify_t why,
	const git_diff_delta *delta,
95
	const git_index_entry *wditem)
96
{
97
	git_diff_file wdfile;
98
	const git_diff_file *baseline = NULL, *target = NULL, *workdir = NULL;
99
	const char *path = NULL;
100

101 102
	if (!data->opts.notify_cb ||
		(why & data->opts.notify_flags) == 0)
103 104
		return 0;

105 106
	if (wditem) {
		memset(&wdfile, 0, sizeof(wdfile));
107

108
		git_oid_cpy(&wdfile.id, &wditem->id);
109 110
		wdfile.path = wditem->path;
		wdfile.size = wditem->file_size;
111
		wdfile.flags = GIT_DIFF_FLAG_VALID_ID;
112
		wdfile.mode = wditem->mode;
113

114
		workdir = &wdfile;
115 116

		path = wditem->path;
117 118
	}

119
	if (delta) {
120 121 122 123 124
		switch (delta->status) {
		case GIT_DELTA_UNMODIFIED:
		case GIT_DELTA_MODIFIED:
		case GIT_DELTA_TYPECHANGE:
		default:
125 126
			baseline = &delta->old_file;
			target = &delta->new_file;
127 128 129 130
			break;
		case GIT_DELTA_ADDED:
		case GIT_DELTA_IGNORED:
		case GIT_DELTA_UNTRACKED:
131
		case GIT_DELTA_UNREADABLE:
132
			target = &delta->new_file;
133 134
			break;
		case GIT_DELTA_DELETED:
135
			baseline = &delta->old_file;
136 137
			break;
		}
138 139

		path = delta->old_file.path;
140 141
	}

142 143 144 145
	{
		int error = data->opts.notify_cb(
			why, path, baseline, target, workdir, data->opts.notify_payload);

146
		return git_error_set_after_callback_function(
147 148
			error, "git_checkout notification");
	}
149 150
}

151 152 153 154 155 156 157 158 159
GIT_INLINE(bool) is_workdir_base_or_new(
	const git_oid *workdir_id,
	const git_diff_file *baseitem,
	const git_diff_file *newitem)
{
	return (git_oid__cmp(&baseitem->id, workdir_id) == 0 ||
		git_oid__cmp(&newitem->id, workdir_id) == 0);
}

160
GIT_INLINE(bool) is_filemode_changed(git_filemode_t a, git_filemode_t b, int respect_filemode)
161
{
162 163 164 165 166 167 168 169 170 171 172 173
	/* If core.filemode = false, ignore links in the repository and executable bit changes */
	if (!respect_filemode) {
		if (a == S_IFLNK)
			a = GIT_FILEMODE_BLOB;
		if (b == S_IFLNK)
			b = GIT_FILEMODE_BLOB;

		a &= ~0111;
		b &= ~0111;
	}

	return (a != b);
174 175
}

176
static bool checkout_is_workdir_modified(
177
	checkout_data *data,
178
	const git_diff_file *baseitem,
179
	const git_diff_file *newitem,
180
	const git_index_entry *wditem)
181 182
{
	git_oid oid;
183
	const git_index_entry *ie;
184

185 186 187 188 189
	/* handle "modified" submodule */
	if (wditem->mode == GIT_FILEMODE_COMMIT) {
		git_submodule *sm;
		unsigned int sm_status = 0;
		const git_oid *sm_oid = NULL;
190
		bool rval = false;
191

192
		if (git_submodule_lookup(&sm, data->repo, wditem->path) < 0) {
193
			git_error_clear();
194
			return true;
195
		}
196

197
		if (git_submodule_status(&sm_status, data->repo, wditem->path, GIT_SUBMODULE_IGNORE_UNSPECIFIED) < 0 ||
198
		    GIT_SUBMODULE_STATUS_IS_WD_DIRTY(sm_status))
199 200 201 202 203
			rval = true;
		else if ((sm_oid = git_submodule_wd_id(sm)) == NULL)
			rval = false;
		else
			rval = (git_oid__cmp(&baseitem->id, sm_oid) != 0);
204

205 206
		git_submodule_free(sm);
		return rval;
207 208
	}

209 210 211 212 213 214
	/*
	 * Look at the cache to decide if the workdir is modified: if the
	 * cache contents match the workdir contents, then we do not need
	 * to examine the working directory directly, instead we can
	 * examine the cache to see if _it_ has been modified.  This allows
	 * us to avoid touching the disk.
215
	 */
216 217 218
	ie = git_index_get_bypath(data->index, wditem->path, 0);

	if (ie != NULL &&
219 220 221 222
	    !git_index_entry_newer_than_index(ie, data->index) &&
	    git_index_time_eq(&wditem->mtime, &ie->mtime) &&
	    wditem->file_size == ie->file_size &&
	    !is_filemode_changed(wditem->mode, ie->mode, data->respect_filemode)) {
223 224 225

		/* The workdir is modified iff the index entry is modified */
		return !is_workdir_base_or_new(&ie->id, baseitem, newitem) ||
226
			is_filemode_changed(baseitem->mode, ie->mode, data->respect_filemode);
227 228
	}

229 230 231 232
	/* depending on where base is coming from, we may or may not know
	 * the actual size of the data, so we can't rely on this shortcut.
	 */
	if (baseitem->size && wditem->file_size != baseitem->size)
233 234
		return true;

235 236 237 238
	/* if the workdir item is a directory, it cannot be a modified file */
	if (S_ISDIR(wditem->mode))
		return false;

239
	if (is_filemode_changed(baseitem->mode, wditem->mode, data->respect_filemode))
240 241
		return true;

242
	if (git_diff__oid_for_entry(&oid, data->diff, wditem, wditem->mode, NULL) < 0)
243 244
		return false;

245 246 247 248
	/* Allow the checkout if the workdir is not modified *or* if the checkout
	 * target's contents are already in the working directory.
	 */
	return !is_workdir_base_or_new(&oid, baseitem, newitem);
249 250 251 252 253 254
}

#define CHECKOUT_ACTION_IF(FLAG,YES,NO) \
	((data->strategy & GIT_CHECKOUT_##FLAG) ? CHECKOUT_ACTION__##YES : CHECKOUT_ACTION__##NO)

static int checkout_action_common(
255
	int *action,
256
	checkout_data *data,
257
	const git_diff_delta *delta,
258 259 260 261 262
	const git_index_entry *wd)
{
	git_checkout_notify_t notify = GIT_CHECKOUT_NOTIFY_NONE;

	if ((data->strategy & GIT_CHECKOUT_UPDATE_ONLY) != 0)
263
		*action = (*action & ~CHECKOUT_ACTION__REMOVE);
264

265
	if ((*action & CHECKOUT_ACTION__UPDATE_BLOB) != 0) {
266
		if (S_ISGITLINK(delta->new_file.mode))
267
			*action = (*action & ~CHECKOUT_ACTION__UPDATE_BLOB) |
268 269
				CHECKOUT_ACTION__UPDATE_SUBMODULE;

270 271
		/* to "update" a symlink, we must remove the old one first */
		if (delta->new_file.mode == GIT_FILEMODE_LINK && wd != NULL)
272
			*action |= CHECKOUT_ACTION__REMOVE;
273

274 275
		/* if the file is on disk and doesn't match our mode, force update */
		if (wd &&
276 277
		    GIT_PERMS_IS_EXEC(wd->mode) != GIT_PERMS_IS_EXEC(delta->new_file.mode))
			*action |= CHECKOUT_ACTION__REMOVE;
278

279 280 281
		notify = GIT_CHECKOUT_NOTIFY_UPDATED;
	}

282
	if ((*action & CHECKOUT_ACTION__CONFLICT) != 0)
283 284
		notify = GIT_CHECKOUT_NOTIFY_CONFLICT;

285
	return checkout_notify(data, notify, delta, wd);
286 287 288
}

static int checkout_action_no_wd(
289
	int *action,
290 291
	checkout_data *data,
	const git_diff_delta *delta)
292
{
293 294 295
	int error = 0;

	*action = CHECKOUT_ACTION__NONE;
296

297 298
	switch (delta->status) {
	case GIT_DELTA_UNMODIFIED: /* case 12 */
299 300 301
		error = checkout_notify(data, GIT_CHECKOUT_NOTIFY_DIRTY, delta, NULL);
		if (error)
			return error;
302
		*action = CHECKOUT_ACTION_IF(RECREATE_MISSING, UPDATE_BLOB, NONE);
303 304
		break;
	case GIT_DELTA_ADDED:    /* case 2 or 28 (and 5 but not really) */
305
		*action = CHECKOUT_ACTION_IF(SAFE, UPDATE_BLOB, NONE);
306
		break;
307
	case GIT_DELTA_MODIFIED: /* case 13 (and 35 but not really) */
308
		*action = CHECKOUT_ACTION_IF(RECREATE_MISSING, UPDATE_BLOB, CONFLICT);
309
		break;
310 311
	case GIT_DELTA_TYPECHANGE: /* case 21 (B->T) and 28 (T->B)*/
		if (delta->new_file.mode == GIT_FILEMODE_TREE)
312
			*action = CHECKOUT_ACTION_IF(SAFE, UPDATE_BLOB, NONE);
313 314
		break;
	case GIT_DELTA_DELETED: /* case 8 or 25 */
315
		*action = CHECKOUT_ACTION_IF(SAFE, REMOVE, NONE);
316
		break;
317 318
	default: /* impossible */
		break;
319 320
	}

321
	return checkout_action_common(action, data, delta, NULL);
322 323
}

324 325
static int checkout_target_fullpath(
	git_buf **out, checkout_data *data, const char *path)
326
{
327 328 329 330 331 332 333 334 335 336 337 338 339 340
	git_buf_truncate(&data->target_path, data->target_len);

	if (path && git_buf_puts(&data->target_path, path) < 0)
		return -1;

	*out = &data->target_path;

	return 0;
}

static bool wd_item_is_removable(
	checkout_data *data, const git_index_entry *wd)
{
	git_buf *full;
341 342 343

	if (wd->mode != GIT_FILEMODE_TREE)
		return true;
344 345 346 347

	if (checkout_target_fullpath(&full, data, wd->path) < 0)
		return false;

348 349 350
	return !full || !git_path_contains(full, DOT_GIT);
}

351 352 353
static int checkout_queue_remove(checkout_data *data, const char *path)
{
	char *copy = git_pool_strdup(&data->pool, path);
354
	GIT_ERROR_CHECK_ALLOC(copy);
355 356 357 358
	return git_vector_insert(&data->removes, copy);
}

/* note that this advances the iterator over the wd item */
359 360 361
static int checkout_action_wd_only(
	checkout_data *data,
	git_iterator *workdir,
362
	const git_index_entry **wditem,
363 364
	git_vector *pathspec)
{
365
	int error = 0;
366
	bool remove = false;
367
	git_checkout_notify_t notify = GIT_CHECKOUT_NOTIFY_NONE;
368
	const git_index_entry *wd = *wditem;
369

370
	if (!git_pathspec__match(
371 372
			pathspec, wd->path,
			(data->strategy & GIT_CHECKOUT_DISABLE_PATHSPEC_MATCH) != 0,
373 374 375 376 377 378 379
			git_iterator_ignore_case(workdir), NULL, NULL)) {

		if (wd->mode == GIT_FILEMODE_TREE)
			return git_iterator_advance_into(wditem, workdir);
		else
			return git_iterator_advance(wditem, workdir);
	}
380

381
	/* check if item is tracked in the index but not in the checkout diff */
382
	if (data->index != NULL) {
383 384
		size_t pos;

385
		error = git_index__find_pos(
386 387
			&pos, data->index, wd->path, 0, GIT_INDEX_STAGE_ANY);

388
		if (wd->mode != GIT_FILEMODE_TREE) {
389
			if (!error) { /* found by git_index__find_pos call */
390 391
				notify = GIT_CHECKOUT_NOTIFY_DIRTY;
				remove = ((data->strategy & GIT_CHECKOUT_FORCE) != 0);
392 393
			} else if (error != GIT_ENOTFOUND)
				return error;
394
			else
395
				error = 0; /* git_index__find_pos does not set error msg */
396 397 398 399 400 401
		} else {
			/* for tree entries, we have to see if there are any index
			 * entries that are contained inside that tree
			 */
			const git_index_entry *e = git_index_get_byindex(data->index, pos);

402 403
			if (e != NULL && data->diff->pfxcomp(e->path, wd->path) == 0)
				return git_iterator_advance_into(wditem, workdir);
404
		}
405
	}
406

407 408 409 410 411
	if (notify != GIT_CHECKOUT_NOTIFY_NONE) {
		/* if we found something in the index, notify and advance */
		if ((error = checkout_notify(data, notify, NULL, wd)) != 0)
			return error;

412
		if (remove && wd_item_is_removable(data, wd))
413 414 415 416 417 418
			error = checkout_queue_remove(data, wd->path);

		if (!error)
			error = git_iterator_advance(wditem, workdir);
	} else {
		/* untracked or ignored - can't know which until we advance through */
419
		bool over = false, removable = wd_item_is_removable(data, wd);
420
		git_iterator_status_t untracked_state;
421 422 423 424 425

		/* copy the entry for issuing notification callback later */
		git_index_entry saved_wd = *wd;
		git_buf_sets(&data->tmp, wd->path);
		saved_wd.path = data->tmp.ptr;
426

427
		error = git_iterator_advance_over(
428
			wditem, &untracked_state, workdir);
429 430 431 432
		if (error == GIT_ITEROVER)
			over = true;
		else if (error < 0)
			return error;
433

434
		if (untracked_state == GIT_ITERATOR_STATUS_IGNORED) {
435 436 437 438 439 440
			notify = GIT_CHECKOUT_NOTIFY_IGNORED;
			remove = ((data->strategy & GIT_CHECKOUT_REMOVE_IGNORED) != 0);
		} else {
			notify = GIT_CHECKOUT_NOTIFY_UNTRACKED;
			remove = ((data->strategy & GIT_CHECKOUT_REMOVE_UNTRACKED) != 0);
		}
441

442 443 444 445 446 447 448 449
		if ((error = checkout_notify(data, notify, NULL, &saved_wd)) != 0)
			return error;

		if (remove && removable)
			error = checkout_queue_remove(data, saved_wd.path);

		if (!error && over) /* restore ITEROVER if needed */
			error = GIT_ITEROVER;
450 451
	}

452
	return error;
453 454
}

455 456 457 458 459 460
static bool submodule_is_config_only(
	checkout_data *data,
	const char *path)
{
	git_submodule *sm = NULL;
	unsigned int sm_loc = 0;
461
	bool rval = false;
462

463
	if (git_submodule_lookup(&sm, data->repo, path) < 0)
464 465
		return true;

466 467 468 469 470 471
	if (git_submodule_location(&sm_loc, sm) < 0 ||
		sm_loc == GIT_SUBMODULE_STATUS_IN_CONFIG)
		rval = true;

	git_submodule_free(sm);

472
	return rval;
473 474
}

475 476
static bool checkout_is_empty_dir(checkout_data *data, const char *path)
{
477 478 479
	git_buf *fullpath;

	if (checkout_target_fullpath(&fullpath, data, path) < 0)
480
		return false;
481 482

	return git_path_is_empty_dir(fullpath->ptr);
483 484
}

485
static int checkout_action_with_wd(
486
	int *action,
487 488
	checkout_data *data,
	const git_diff_delta *delta,
489
	git_iterator *workdir,
490 491
	const git_index_entry *wd)
{
492
	*action = CHECKOUT_ACTION__NONE;
493 494 495

	switch (delta->status) {
	case GIT_DELTA_UNMODIFIED: /* case 14/15 or 33 */
496
		if (checkout_is_workdir_modified(data, &delta->old_file, &delta->new_file, wd)) {
497
			GIT_ERROR_CHECK_ERROR(
498 499
				checkout_notify(data, GIT_CHECKOUT_NOTIFY_DIRTY, delta, wd) );
			*action = CHECKOUT_ACTION_IF(FORCE, UPDATE_BLOB, NONE);
500
		}
501 502
		break;
	case GIT_DELTA_ADDED: /* case 3, 4 or 6 */
503 504 505 506
		if (git_iterator_current_is_ignored(workdir))
			*action = CHECKOUT_ACTION_IF(DONT_OVERWRITE_IGNORED, CONFLICT, UPDATE_BLOB);
		else
			*action = CHECKOUT_ACTION_IF(FORCE, UPDATE_BLOB, CONFLICT);
507 508
		break;
	case GIT_DELTA_DELETED: /* case 9 or 10 (or 26 but not really) */
509
		if (checkout_is_workdir_modified(data, &delta->old_file, &delta->new_file, wd))
510
			*action = CHECKOUT_ACTION_IF(FORCE, REMOVE, CONFLICT);
511
		else
512
			*action = CHECKOUT_ACTION_IF(SAFE, REMOVE, NONE);
513 514
		break;
	case GIT_DELTA_MODIFIED: /* case 16, 17, 18 (or 36 but not really) */
515 516
		if (wd->mode != GIT_FILEMODE_COMMIT &&
			checkout_is_workdir_modified(data, &delta->old_file, &delta->new_file, wd))
517
			*action = CHECKOUT_ACTION_IF(FORCE, UPDATE_BLOB, CONFLICT);
518
		else
519
			*action = CHECKOUT_ACTION_IF(SAFE, UPDATE_BLOB, NONE);
520 521
		break;
	case GIT_DELTA_TYPECHANGE: /* case 22, 23, 29, 30 */
522 523 524 525 526
		if (delta->old_file.mode == GIT_FILEMODE_TREE) {
			if (wd->mode == GIT_FILEMODE_TREE)
				/* either deleting items in old tree will delete the wd dir,
				 * or we'll get a conflict when we attempt blob update...
				 */
527
				*action = CHECKOUT_ACTION_IF(SAFE, UPDATE_BLOB, NONE);
528 529 530 531 532
			else if (wd->mode == GIT_FILEMODE_COMMIT) {
				/* workdir is possibly a "phantom" submodule - treat as a
				 * tree if the only submodule info came from the config
				 */
				if (submodule_is_config_only(data, wd->path))
533
					*action = CHECKOUT_ACTION_IF(SAFE, UPDATE_BLOB, NONE);
534
				else
535
					*action = CHECKOUT_ACTION_IF(FORCE, REMOVE_AND_UPDATE, CONFLICT);
536
			} else
537
				*action = CHECKOUT_ACTION_IF(FORCE, REMOVE, CONFLICT);
538
		}
539
		else if (checkout_is_workdir_modified(data, &delta->old_file, &delta->new_file, wd))
540
			*action = CHECKOUT_ACTION_IF(FORCE, REMOVE_AND_UPDATE, CONFLICT);
541
		else
542
			*action = CHECKOUT_ACTION_IF(SAFE, REMOVE_AND_UPDATE, NONE);
543 544 545

		/* don't update if the typechange is to a tree */
		if (delta->new_file.mode == GIT_FILEMODE_TREE)
546
			*action = (*action & ~CHECKOUT_ACTION__UPDATE_BLOB);
547 548 549
		break;
	default: /* impossible */
		break;
550 551
	}

552
	return checkout_action_common(action, data, delta, wd);
553
}
554

555
static int checkout_action_with_wd_blocker(
556
	int *action,
557 558 559 560
	checkout_data *data,
	const git_diff_delta *delta,
	const git_index_entry *wd)
{
561
	*action = CHECKOUT_ACTION__NONE;
562

563 564 565
	switch (delta->status) {
	case GIT_DELTA_UNMODIFIED:
		/* should show delta as dirty / deleted */
566
		GIT_ERROR_CHECK_ERROR(
567 568
			checkout_notify(data, GIT_CHECKOUT_NOTIFY_DIRTY, delta, wd) );
		*action = CHECKOUT_ACTION_IF(FORCE, REMOVE_AND_UPDATE, NONE);
569 570 571
		break;
	case GIT_DELTA_ADDED:
	case GIT_DELTA_MODIFIED:
572
		*action = CHECKOUT_ACTION_IF(FORCE, REMOVE_AND_UPDATE, CONFLICT);
573 574
		break;
	case GIT_DELTA_DELETED:
575
		*action = CHECKOUT_ACTION_IF(FORCE, REMOVE, CONFLICT);
576 577 578
		break;
	case GIT_DELTA_TYPECHANGE:
		/* not 100% certain about this... */
579
		*action = CHECKOUT_ACTION_IF(FORCE, REMOVE_AND_UPDATE, CONFLICT);
580 581 582
		break;
	default: /* impossible */
		break;
583 584
	}

585
	return checkout_action_common(action, data, delta, wd);
586 587 588
}

static int checkout_action_with_wd_dir(
589
	int *action,
590 591
	checkout_data *data,
	const git_diff_delta *delta,
592
	git_iterator *workdir,
593 594
	const git_index_entry *wd)
{
595
	*action = CHECKOUT_ACTION__NONE;
596 597 598

	switch (delta->status) {
	case GIT_DELTA_UNMODIFIED: /* case 19 or 24 (or 34 but not really) */
599
		GIT_ERROR_CHECK_ERROR(
600
			checkout_notify(data, GIT_CHECKOUT_NOTIFY_DIRTY, delta, NULL));
601
		GIT_ERROR_CHECK_ERROR(
602
			checkout_notify(data, GIT_CHECKOUT_NOTIFY_UNTRACKED, NULL, wd));
603
		*action = CHECKOUT_ACTION_IF(FORCE, REMOVE_AND_UPDATE, NONE);
604 605 606
		break;
	case GIT_DELTA_ADDED:/* case 4 (and 7 for dir) */
	case GIT_DELTA_MODIFIED: /* case 20 (or 37 but not really) */
607 608 609
		if (delta->old_file.mode == GIT_FILEMODE_COMMIT)
			/* expected submodule (and maybe found one) */;
		else if (delta->new_file.mode != GIT_FILEMODE_TREE)
610 611 612
			*action = git_iterator_current_is_ignored(workdir) ?
				CHECKOUT_ACTION_IF(DONT_OVERWRITE_IGNORED, CONFLICT, REMOVE_AND_UPDATE) :
				CHECKOUT_ACTION_IF(FORCE, REMOVE_AND_UPDATE, CONFLICT);
613 614
		break;
	case GIT_DELTA_DELETED: /* case 11 (and 27 for dir) */
615
		if (delta->old_file.mode != GIT_FILEMODE_TREE)
616
			GIT_ERROR_CHECK_ERROR(
617
				checkout_notify(data, GIT_CHECKOUT_NOTIFY_UNTRACKED, NULL, wd));
618 619 620
		break;
	case GIT_DELTA_TYPECHANGE: /* case 24 or 31 */
		if (delta->old_file.mode == GIT_FILEMODE_TREE) {
621 622 623 624 625 626
			/* For typechange from dir, remove dir and add blob, but it is
			 * not safe to remove dir if it contains modified files.
			 * However, safely removing child files will remove the parent
			 * directory if is it left empty, so we can defer removing the
			 * dir and it will succeed if no children are left.
			 */
627
			*action = CHECKOUT_ACTION_IF(SAFE, UPDATE_BLOB, NONE);
628
		}
629 630
		else if (delta->new_file.mode != GIT_FILEMODE_TREE)
			/* For typechange to dir, dir is already created so no action */
631
			*action = CHECKOUT_ACTION_IF(FORCE, REMOVE_AND_UPDATE, CONFLICT);
632 633 634
		break;
	default: /* impossible */
		break;
635 636
	}

637
	return checkout_action_common(action, data, delta, wd);
638 639
}

640 641 642 643 644 645 646 647 648 649 650 651 652 653
static int checkout_action_with_wd_dir_empty(
	int *action,
	checkout_data *data,
	const git_diff_delta *delta)
{
	int error = checkout_action_no_wd(action, data, delta);

	/* We can always safely remove an empty directory. */
	if (error == 0 && *action != CHECKOUT_ACTION__NONE)
		*action |= CHECKOUT_ACTION__REMOVE;

	return error;
}

654
static int checkout_action(
655
	int *action,
656
	checkout_data *data,
657
	git_diff_delta *delta,
658
	git_iterator *workdir,
659
	const git_index_entry **wditem,
660 661
	git_vector *pathspec)
{
662
	int cmp = -1, error;
663 664
	int (*strcomp)(const char *, const char *) = data->diff->strcomp;
	int (*pfxcomp)(const char *str, const char *pfx) = data->diff->pfxcomp;
665
	int (*advance)(const git_index_entry **, git_iterator *) = NULL;
666 667 668 669

	/* move workdir iterator to follow along with deltas */

	while (1) {
670 671
		const git_index_entry *wd = *wditem;

672
		if (!wd)
673
			return checkout_action_no_wd(action, data, delta);
674

675 676 677 678 679 680 681 682 683 684 685 686 687
		cmp = strcomp(wd->path, delta->old_file.path);

		/* 1. wd before delta ("a/a" before "a/b")
		 * 2. wd prefixes delta & should expand ("a/" before "a/b")
		 * 3. wd prefixes delta & cannot expand ("a/b" before "a/b/c")
		 * 4. wd equals delta ("a/b" and "a/b")
		 * 5. wd after delta & delta prefixes wd ("a/b/c" after "a/b/" or "a/b")
		 * 6. wd after delta ("a/c" after "a/b")
		 */

		if (cmp < 0) {
			cmp = pfxcomp(delta->old_file.path, wd->path);

688
			if (cmp == 0) {
689 690
				if (wd->mode == GIT_FILEMODE_TREE) {
					/* case 2 - entry prefixed by workdir tree */
691
					error = git_iterator_advance_into(wditem, workdir);
692 693
					if (error < 0 && error != GIT_ITEROVER)
						goto done;
694 695 696 697 698
					continue;
				}

				/* case 3 maybe - wd contains non-dir where dir expected */
				if (delta->old_file.path[strlen(wd->path)] == '/') {
699 700 701 702
					error = checkout_action_with_wd_blocker(
						action, data, delta, wd);
					advance = git_iterator_advance;
					goto done;
703
				}
704
			}
705

706
			/* case 1 - handle wd item (if it matches pathspec) */
707 708
			error = checkout_action_wd_only(data, workdir, wditem, pathspec);
			if (error && error != GIT_ITEROVER)
709
				goto done;
710 711
			continue;
		}
712

713 714
		if (cmp == 0) {
			/* case 4 */
715
			error = checkout_action_with_wd(action, data, delta, workdir, wd);
716 717
			advance = git_iterator_advance;
			goto done;
718
		}
719

720
		cmp = pfxcomp(wd->path, delta->old_file.path);
721

722
		if (cmp == 0) { /* case 5 */
723
			if (wd->path[strlen(delta->old_file.path)] != '/')
724
				return checkout_action_no_wd(action, data, delta);
725 726 727

			if (delta->status == GIT_DELTA_TYPECHANGE) {
				if (delta->old_file.mode == GIT_FILEMODE_TREE) {
728
					error = checkout_action_with_wd(action, data, delta, workdir, wd);
729 730
					advance = git_iterator_advance_into;
					goto done;
731 732 733 734 735 736
				}

				if (delta->new_file.mode == GIT_FILEMODE_TREE ||
					delta->new_file.mode == GIT_FILEMODE_COMMIT ||
					delta->old_file.mode == GIT_FILEMODE_COMMIT)
				{
737
					error = checkout_action_with_wd(action, data, delta, workdir, wd);
738 739
					advance = git_iterator_advance;
					goto done;
740
				}
741 742
			}

743 744 745
			return checkout_is_empty_dir(data, wd->path) ?
				checkout_action_with_wd_dir_empty(action, data, delta) :
				checkout_action_with_wd_dir(action, data, delta, workdir, wd);
746
		}
747

748
		/* case 6 - wd is after delta */
749
		return checkout_action_no_wd(action, data, delta);
750 751
	}

752 753 754 755 756 757 758 759 760
done:
	if (!error && advance != NULL &&
		(error = advance(wditem, workdir)) < 0) {
		*wditem = NULL;
		if (error == GIT_ITEROVER)
			error = 0;
	}

	return error;
761 762
}

763 764 765 766 767 768 769 770
static int checkout_remaining_wd_items(
	checkout_data *data,
	git_iterator *workdir,
	const git_index_entry *wd,
	git_vector *spec)
{
	int error = 0;

771 772
	while (wd && !error)
		error = checkout_action_wd_only(data, workdir, &wd, spec);
773

774 775 776
	if (error == GIT_ITEROVER)
		error = 0;

777 778 779
	return error;
}

780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
GIT_INLINE(int) checkout_idxentry_cmp(
	const git_index_entry *a,
	const git_index_entry *b)
{
	if (!a && !b)
		return 0;
	else if (!a && b)
		return -1;
	else if(a && !b)
		return 1;
	else
		return strcmp(a->path, b->path);
}

static int checkout_conflictdata_cmp(const void *a, const void *b)
{
	const checkout_conflictdata *ca = a;
	const checkout_conflictdata *cb = b;
	int diff;

	if ((diff = checkout_idxentry_cmp(ca->ancestor, cb->ancestor)) == 0 &&
801
	    (diff = checkout_idxentry_cmp(ca->ours, cb->theirs)) == 0)
802 803 804 805 806
		diff = checkout_idxentry_cmp(ca->theirs, cb->theirs);

	return diff;
}

807
static int checkout_conflictdata_empty(
808
	const git_vector *conflicts, size_t idx, void *payload)
809 810 811
{
	checkout_conflictdata *conflict;

812 813
	GIT_UNUSED(payload);

814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
	if ((conflict = git_vector_get(conflicts, idx)) == NULL)
		return -1;

	if (conflict->ancestor || conflict->ours || conflict->theirs)
		return 0;

	git__free(conflict);
	return 1;
}

GIT_INLINE(bool) conflict_pathspec_match(
	checkout_data *data,
	git_iterator *workdir,
	git_vector *pathspec,
	const git_index_entry *ancestor,
	const git_index_entry *ours,
	const git_index_entry *theirs)
{
	/* if the pathspec matches ours *or* theirs, proceed */
	if (ours && git_pathspec__match(pathspec, ours->path,
		(data->strategy & GIT_CHECKOUT_DISABLE_PATHSPEC_MATCH) != 0,
		git_iterator_ignore_case(workdir), NULL, NULL))
		return true;

	if (theirs && git_pathspec__match(pathspec, theirs->path,
		(data->strategy & GIT_CHECKOUT_DISABLE_PATHSPEC_MATCH) != 0,
		git_iterator_ignore_case(workdir), NULL, NULL))
		return true;

	if (ancestor && git_pathspec__match(pathspec, ancestor->path,
		(data->strategy & GIT_CHECKOUT_DISABLE_PATHSPEC_MATCH) != 0,
		git_iterator_ignore_case(workdir), NULL, NULL))
		return true;

	return false;
}

Edward Thomson committed
851 852 853 854 855 856 857 858
GIT_INLINE(int) checkout_conflict_detect_submodule(checkout_conflictdata *conflict)
{
	conflict->submodule = ((conflict->ancestor && S_ISGITLINK(conflict->ancestor->mode)) ||
		(conflict->ours && S_ISGITLINK(conflict->ours->mode)) ||
		(conflict->theirs && S_ISGITLINK(conflict->theirs->mode)));
	return 0;
}

859 860 861 862 863
GIT_INLINE(int) checkout_conflict_detect_binary(git_repository *repo, checkout_conflictdata *conflict)
{
	git_blob *ancestor_blob = NULL, *our_blob = NULL, *their_blob = NULL;
	int error = 0;

Edward Thomson committed
864 865 866
	if (conflict->submodule)
		return 0;

867
	if (conflict->ancestor) {
868
		if ((error = git_blob_lookup(&ancestor_blob, repo, &conflict->ancestor->id)) < 0)
869 870 871 872 873 874
			goto done;

		conflict->binary = git_blob_is_binary(ancestor_blob);
	}

	if (!conflict->binary && conflict->ours) {
875
		if ((error = git_blob_lookup(&our_blob, repo, &conflict->ours->id)) < 0)
876 877 878 879 880 881
			goto done;

		conflict->binary = git_blob_is_binary(our_blob);
	}

	if (!conflict->binary && conflict->theirs) {
882
		if ((error = git_blob_lookup(&their_blob, repo, &conflict->theirs->id)) < 0)
883 884 885 886 887 888 889 890 891 892 893 894 895
			goto done;

		conflict->binary = git_blob_is_binary(their_blob);
	}

done:
	git_blob_free(ancestor_blob);
	git_blob_free(our_blob);
	git_blob_free(their_blob);

	return error;
}

896 897 898 899 900 901 902 903 904 905 906
static int checkout_conflict_append_update(
	const git_index_entry *ancestor,
	const git_index_entry *ours,
	const git_index_entry *theirs,
	void *payload)
{
	checkout_data *data = payload;
	checkout_conflictdata *conflict;
	int error;

	conflict = git__calloc(1, sizeof(checkout_conflictdata));
907
	GIT_ERROR_CHECK_ALLOC(conflict);
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932

	conflict->ancestor = ancestor;
	conflict->ours = ours;
	conflict->theirs = theirs;

	if ((error = checkout_conflict_detect_submodule(conflict)) < 0 ||
		(error = checkout_conflict_detect_binary(data->repo, conflict)) < 0)
	{
		git__free(conflict);
		return error;
	}

	if (git_vector_insert(&data->update_conflicts, conflict))
		return -1;

	return 0;
}

static int checkout_conflicts_foreach(
	checkout_data *data,
	git_index *index,
	git_iterator *workdir,
	git_vector *pathspec,
	int (*cb)(const git_index_entry *, const git_index_entry *, const git_index_entry *, void *),
	void *payload)
933 934 935 936 937
{
	git_index_conflict_iterator *iterator = NULL;
	const git_index_entry *ancestor, *ours, *theirs;
	int error = 0;

938
	if ((error = git_index_conflict_iterator_new(&iterator, index)) < 0)
939 940 941 942 943 944 945
		goto done;

	/* Collect the conflicts */
	while ((error = git_index_conflict_next(&ancestor, &ours, &theirs, iterator)) == 0) {
		if (!conflict_pathspec_match(data, workdir, pathspec, ancestor, ours, theirs))
			continue;

946
		if ((error = cb(ancestor, ours, theirs, payload)) < 0)
947
			goto done;
948 949 950 951 952 953 954 955 956 957 958
	}

	if (error == GIT_ITEROVER)
		error = 0;

done:
	git_index_conflict_iterator_free(iterator);

	return error;
}

959 960 961 962 963
static int checkout_conflicts_load(checkout_data *data, git_iterator *workdir, git_vector *pathspec)
{
	git_index *index;

	/* Only write conficts from sources that have them: indexes. */
964
	if ((index = git_iterator_index(data->target)) == NULL)
965 966 967 968 969 970 971 972 973 974 975 976 977 978
		return 0;

	data->update_conflicts._cmp = checkout_conflictdata_cmp;

	if (checkout_conflicts_foreach(data, index, workdir, pathspec, checkout_conflict_append_update, data) < 0)
		return -1;

	/* Collect the REUC and NAME entries */
	data->update_reuc = &index->reuc;
	data->update_names = &index->names;

	return 0;
}

979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
GIT_INLINE(int) checkout_conflicts_cmp_entry(
	const char *path,
	const git_index_entry *entry)
{
	return strcmp((const char *)path, entry->path);
}

static int checkout_conflicts_cmp_ancestor(const void *p, const void *c)
{
	const char *path = p;
	const checkout_conflictdata *conflict = c;

	if (!conflict->ancestor)
		return 1;

	return checkout_conflicts_cmp_entry(path, conflict->ancestor);
}

static checkout_conflictdata *checkout_conflicts_search_ancestor(
	checkout_data *data,
	const char *path)
{
	size_t pos;

1003
	if (git_vector_bsearch2(&pos, &data->update_conflicts, checkout_conflicts_cmp_ancestor, path) < 0)
1004 1005
		return NULL;

1006
	return git_vector_get(&data->update_conflicts, pos);
1007 1008 1009 1010 1011 1012 1013 1014 1015
}

static checkout_conflictdata *checkout_conflicts_search_branch(
	checkout_data *data,
	const char *path)
{
	checkout_conflictdata *conflict;
	size_t i;

1016
	git_vector_foreach(&data->update_conflicts, i, conflict) {
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
		int cmp = -1;

		if (conflict->ancestor)
			break;

		if (conflict->ours)
			cmp = checkout_conflicts_cmp_entry(path, conflict->ours);
		else if (conflict->theirs)
			cmp = checkout_conflicts_cmp_entry(path, conflict->theirs);

		if (cmp == 0)
			return conflict;
	}

	return NULL;
}

static int checkout_conflicts_load_byname_entry(
	checkout_conflictdata **ancestor_out,
	checkout_conflictdata **ours_out,
	checkout_conflictdata **theirs_out,
	checkout_data *data,
	const git_index_name_entry *name_entry)
{
	checkout_conflictdata *ancestor, *ours = NULL, *theirs = NULL;
	int error = 0;

	*ancestor_out = NULL;
	*ours_out = NULL;
	*theirs_out = NULL;

	if (!name_entry->ancestor) {
1049
		git_error_set(GIT_ERROR_INDEX, "a NAME entry exists without an ancestor");
1050 1051 1052 1053 1054
		error = -1;
		goto done;
	}

	if (!name_entry->ours && !name_entry->theirs) {
1055
		git_error_set(GIT_ERROR_INDEX, "a NAME entry exists without an ours or theirs");
1056 1057 1058 1059 1060 1061
		error = -1;
		goto done;
	}

	if ((ancestor = checkout_conflicts_search_ancestor(data,
		name_entry->ancestor)) == NULL) {
1062
		git_error_set(GIT_ERROR_INDEX,
1063
			"a NAME entry referenced ancestor entry '%s' which does not exist in the main index",
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
			name_entry->ancestor);
		error = -1;
		goto done;
	}

	if (name_entry->ours) {
		if (strcmp(name_entry->ancestor, name_entry->ours) == 0)
			ours = ancestor;
		else if ((ours = checkout_conflicts_search_branch(data, name_entry->ours)) == NULL ||
			ours->ours == NULL) {
1074
			git_error_set(GIT_ERROR_INDEX,
1075
				"a NAME entry referenced our entry '%s' which does not exist in the main index",
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
				name_entry->ours);
			error = -1;
			goto done;
		}
	}

	if (name_entry->theirs) {
		if (strcmp(name_entry->ancestor, name_entry->theirs) == 0)
			theirs = ancestor;
		else if (name_entry->ours && strcmp(name_entry->ours, name_entry->theirs) == 0)
			theirs = ours;
		else if ((theirs = checkout_conflicts_search_branch(data, name_entry->theirs)) == NULL ||
			theirs->theirs == NULL) {
1089
			git_error_set(GIT_ERROR_INDEX,
1090
				"a NAME entry referenced their entry '%s' which does not exist in the main index",
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
				name_entry->theirs);
			error = -1;
			goto done;
		}
	}

	*ancestor_out = ancestor;
	*ours_out = ours;
	*theirs_out = theirs;

done:
	return error;
}

static int checkout_conflicts_coalesce_renames(
	checkout_data *data)
{
1108
	git_index *index;
1109 1110 1111 1112 1113
	const git_index_name_entry *name_entry;
	checkout_conflictdata *ancestor_conflict, *our_conflict, *their_conflict;
	size_t i, names;
	int error = 0;

1114
	if ((index = git_iterator_index(data->target)) == NULL)
1115 1116
		return 0;

1117
	/* Juggle entries based on renames */
1118
	names = git_index_name_entrycount(index);
Russell Belfer committed
1119

1120
	for (i = 0; i < names; i++) {
1121
		name_entry = git_index_name_get_byindex(index, i);
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154

		if ((error = checkout_conflicts_load_byname_entry(
			&ancestor_conflict, &our_conflict, &their_conflict,
			data, name_entry)) < 0)
			goto done;

		if (our_conflict && our_conflict != ancestor_conflict) {
			ancestor_conflict->ours = our_conflict->ours;
			our_conflict->ours = NULL;

			if (our_conflict->theirs)
				our_conflict->name_collision = 1;

			if (our_conflict->name_collision)
				ancestor_conflict->name_collision = 1;
		}

		if (their_conflict && their_conflict != ancestor_conflict) {
			ancestor_conflict->theirs = their_conflict->theirs;
			their_conflict->theirs = NULL;

			if (their_conflict->ours)
				their_conflict->name_collision = 1;

			if (their_conflict->name_collision)
				ancestor_conflict->name_collision = 1;
		}

		if (our_conflict && our_conflict != ancestor_conflict &&
			their_conflict && their_conflict != ancestor_conflict)
			ancestor_conflict->one_to_two = 1;
	}

1155
	git_vector_remove_matching(
1156
		&data->update_conflicts, checkout_conflictdata_empty, NULL);
1157 1158 1159 1160 1161 1162 1163 1164

done:
	return error;
}

static int checkout_conflicts_mark_directoryfile(
	checkout_data *data)
{
1165
	git_index *index;
1166 1167 1168 1169
	checkout_conflictdata *conflict;
	const git_index_entry *entry;
	size_t i, j, len;
	const char *path;
1170
	int prefixed, error = 0;
1171

1172
	if ((index = git_iterator_index(data->target)) == NULL)
1173 1174 1175
		return 0;

	len = git_index_entrycount(index);
1176 1177

	/* Find d/f conflicts */
1178
	git_vector_foreach(&data->update_conflicts, i, conflict) {
1179
		if ((conflict->ours && conflict->theirs) ||
1180
		    (!conflict->ours && !conflict->theirs))
1181 1182 1183 1184 1185
			continue;

		path = conflict->ours ?
			conflict->ours->path : conflict->theirs->path;

1186
		if ((error = git_index_find(&j, index, path)) < 0) {
1187
			if (error == GIT_ENOTFOUND)
1188
				git_error_set(GIT_ERROR_INDEX,
1189
					"index inconsistency, could not find entry for expected conflict '%s'", path);
1190 1191 1192 1193 1194

			goto done;
		}

		for (; j < len; j++) {
1195
			if ((entry = git_index_get_byindex(index, j)) == NULL) {
1196
				git_error_set(GIT_ERROR_INDEX,
1197
					"index inconsistency, truncated index while loading expected conflict '%s'", path);
1198 1199 1200 1201
				error = -1;
				goto done;
			}

1202
			prefixed = git_path_equal_or_prefixed(path, entry->path, NULL);
1203

1204
			if (prefixed == GIT_PATH_EQUAL)
1205 1206
				continue;

1207
			if (prefixed == GIT_PATH_PREFIX)
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
				conflict->directoryfile = 1;

			break;
		}
	}

done:
	return error;
}

1218
static int checkout_get_update_conflicts(
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
	checkout_data *data,
	git_iterator *workdir,
	git_vector *pathspec)
{
	int error = 0;

	if (data->strategy & GIT_CHECKOUT_SKIP_UNMERGED)
		return 0;

	if ((error = checkout_conflicts_load(data, workdir, pathspec)) < 0 ||
1229 1230
	    (error = checkout_conflicts_coalesce_renames(data)) < 0 ||
	    (error = checkout_conflicts_mark_directoryfile(data)) < 0)
1231 1232 1233 1234 1235 1236
		goto done;

done:
	return error;
}

1237 1238 1239 1240 1241 1242 1243 1244 1245
static int checkout_conflict_append_remove(
	const git_index_entry *ancestor,
	const git_index_entry *ours,
	const git_index_entry *theirs,
	void *payload)
{
	checkout_data *data = payload;
	const char *name;

1246 1247
	assert(ancestor || ours || theirs);

1248 1249 1250 1251 1252 1253
	if (ancestor)
		name = git__strdup(ancestor->path);
	else if (ours)
		name = git__strdup(ours->path);
	else if (theirs)
		name = git__strdup(theirs->path);
1254 1255
	else
		abort();
1256

1257
	GIT_ERROR_CHECK_ALLOC(name);
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272

	return git_vector_insert(&data->remove_conflicts, (char *)name);
}

static int checkout_get_remove_conflicts(
	checkout_data *data,
	git_iterator *workdir,
	git_vector *pathspec)
{
	if ((data->strategy & GIT_CHECKOUT_DONT_UPDATE_INDEX) != 0)
		return 0;

	return checkout_conflicts_foreach(data, data->index, workdir, pathspec, checkout_conflict_append_remove, data);
}

1273 1274 1275 1276 1277
static int checkout_verify_paths(
	git_repository *repo,
	int action,
	git_diff_delta *delta)
{
1278
	unsigned int flags = GIT_PATH_REJECT_WORKDIR_DEFAULTS;
1279 1280

	if (action & CHECKOUT_ACTION__REMOVE) {
1281
		if (!git_path_isvalid(repo, delta->old_file.path, delta->old_file.mode, flags)) {
1282
			git_error_set(GIT_ERROR_CHECKOUT, "cannot remove invalid path '%s'", delta->old_file.path);
1283 1284 1285 1286 1287
			return -1;
		}
	}

	if (action & ~CHECKOUT_ACTION__REMOVE) {
1288
		if (!git_path_isvalid(repo, delta->new_file.path, delta->new_file.mode, flags)) {
1289
			git_error_set(GIT_ERROR_CHECKOUT, "cannot checkout to invalid path '%s'", delta->new_file.path);
1290 1291 1292 1293 1294 1295 1296
			return -1;
		}
	}

	return 0;
}

1297 1298 1299
static int checkout_get_actions(
	uint32_t **actions_ptr,
	size_t **counts_ptr,
1300 1301
	checkout_data *data,
	git_iterator *workdir)
1302
{
1303
	int error = 0, act;
1304 1305
	const git_index_entry *wditem;
	git_vector pathspec = GIT_VECTOR_INIT, *deltas;
1306
	git_pool pathpool;
1307 1308 1309 1310
	git_diff_delta *delta;
	size_t i, *counts = NULL;
	uint32_t *actions = NULL;

1311 1312
	if (git_pool_init(&pathpool, 1) < 0)
		return -1;
1313

1314
	if (data->opts.paths.count > 0 &&
1315
	    git_pathspec__vinit(&pathspec, &data->opts.paths, &pathpool) < 0)
1316 1317
		return -1;

1318
	if ((error = git_iterator_current(&wditem, workdir)) < 0 &&
1319
	    error != GIT_ITEROVER)
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
		goto fail;

	deltas = &data->diff->deltas;

	*counts_ptr = counts = git__calloc(CHECKOUT_ACTION__MAX+1, sizeof(size_t));
	*actions_ptr = actions = git__calloc(
		deltas->length ? deltas->length : 1, sizeof(uint32_t));
	if (!counts || !actions) {
		error = -1;
		goto fail;
	}

	git_vector_foreach(deltas, i, delta) {
1333 1334 1335
		if ((error = checkout_action(&act, data, delta, workdir, &wditem, &pathspec)) == 0)
			error = checkout_verify_paths(data->repo, act, delta);

1336
		if (error != 0)
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
			goto fail;

		actions[i] = act;

		if (act & CHECKOUT_ACTION__REMOVE)
			counts[CHECKOUT_ACTION__REMOVE]++;
		if (act & CHECKOUT_ACTION__UPDATE_BLOB)
			counts[CHECKOUT_ACTION__UPDATE_BLOB]++;
		if (act & CHECKOUT_ACTION__UPDATE_SUBMODULE)
			counts[CHECKOUT_ACTION__UPDATE_SUBMODULE]++;
		if (act & CHECKOUT_ACTION__CONFLICT)
			counts[CHECKOUT_ACTION__CONFLICT]++;
	}
1350

1351
	error = checkout_remaining_wd_items(data, workdir, wditem, &pathspec);
1352
	if (error)
1353
		goto fail;
1354

1355 1356 1357
	counts[CHECKOUT_ACTION__REMOVE] += data->removes.length;

	if (counts[CHECKOUT_ACTION__CONFLICT] > 0 &&
1358
	    (data->strategy & GIT_CHECKOUT_ALLOW_CONFLICTS) == 0) {
1359
		git_error_set(GIT_ERROR_CHECKOUT, "%"PRIuZ" %s checkout",
1360
			counts[CHECKOUT_ACTION__CONFLICT],
1361 1362
			counts[CHECKOUT_ACTION__CONFLICT] == 1 ?
			"conflict prevents" : "conflicts prevent");
1363
		error = GIT_ECONFLICT;
1364 1365 1366
		goto fail;
	}

1367

1368
	if ((error = checkout_get_remove_conflicts(data, workdir, &pathspec)) < 0 ||
1369
	    (error = checkout_get_update_conflicts(data, workdir, &pathspec)) < 0)
1370 1371
		goto fail;

1372 1373
	counts[CHECKOUT_ACTION__REMOVE_CONFLICT] = git_vector_length(&data->remove_conflicts);
	counts[CHECKOUT_ACTION__UPDATE_CONFLICT] = git_vector_length(&data->update_conflicts);
1374

1375
	git_pathspec__vfree(&pathspec);
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
	git_pool_clear(&pathpool);

	return 0;

fail:
	*counts_ptr = NULL;
	git__free(counts);
	*actions_ptr = NULL;
	git__free(actions);

1386
	git_pathspec__vfree(&pathspec);
1387 1388 1389 1390 1391
	git_pool_clear(&pathpool);

	return error;
}

1392 1393
static bool should_remove_existing(checkout_data *data)
{
1394
	int ignorecase;
1395

1396
	if (git_repository__configmap_lookup(&ignorecase, data->repo, GIT_CONFIGMAP_IGNORECASE) < 0) {
1397 1398
		ignorecase = 0;
	}
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408

	return (ignorecase &&
		(data->strategy & GIT_CHECKOUT_DONT_REMOVE_EXISTING) == 0);
}

#define MKDIR_NORMAL \
	GIT_MKDIR_PATH | GIT_MKDIR_VERIFY_DIR
#define MKDIR_REMOVE_EXISTING \
	MKDIR_NORMAL | GIT_MKDIR_REMOVE_FILES | GIT_MKDIR_REMOVE_SYMLINKS

1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
static int checkout_mkdir(
	checkout_data *data,
	const char *path,
	const char *base,
	mode_t mode,
	unsigned int flags)
{
	struct git_futils_mkdir_options mkdir_opts = {0};
	int error;

	mkdir_opts.dir_map = data->mkdir_map;
	mkdir_opts.pool = &data->pool;

1422
	error = git_futils_mkdir_relative(
1423 1424 1425 1426 1427 1428 1429 1430 1431
		path, base, mode, flags, &mkdir_opts);

	data->perfdata.mkdir_calls += mkdir_opts.perfdata.mkdir_calls;
	data->perfdata.stat_calls += mkdir_opts.perfdata.stat_calls;
	data->perfdata.chmod_calls += mkdir_opts.perfdata.chmod_calls;

	return error;
}

1432 1433 1434
static int mkpath2file(
	checkout_data *data, const char *path, unsigned int mode)
{
1435 1436
	struct stat st;
	bool remove_existing = should_remove_existing(data);
1437 1438 1439
	unsigned int flags =
		(remove_existing ? MKDIR_REMOVE_EXISTING : MKDIR_NORMAL) |
		GIT_MKDIR_SKIP_LAST;
1440 1441
	int error;

1442 1443
	if ((error = checkout_mkdir(
			data, path, data->opts.target_directory, mode, flags)) < 0)
1444 1445
		return error;

1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
	if (remove_existing) {
		data->perfdata.stat_calls++;

		if (p_lstat(path, &st) == 0) {

			/* Some file, symlink or folder already exists at this name.
			 * We would have removed it in remove_the_old unless we're on
			 * a case inensitive filesystem (or the user has asked us not
			 * to).  Remove the similarly named file to write the new.
			 */
			error = git_futils_rmdir_r(path, NULL, GIT_RMDIR_REMOVE_FILES);
		} else if (errno != ENOENT) {
1458
			git_error_set(GIT_ERROR_OS, "failed to stat '%s'", path);
1459 1460
			return GIT_EEXISTS;
		} else {
1461
			git_error_clear();
1462 1463
		}
	}
1464 1465

	return error;
1466 1467
}

1468
struct checkout_stream {
1469
	git_writestream base;
1470 1471 1472 1473
	const char *path;
	int fd;
	int open;
};
1474

1475
static int checkout_stream_write(
1476
	git_writestream *s, const char *buffer, size_t len)
1477 1478 1479
{
	struct checkout_stream *stream = (struct checkout_stream *)s;
	int ret;
1480

1481
	if ((ret = p_write(stream->fd, buffer, len)) < 0)
1482
		git_error_set(GIT_ERROR_OS, "could not write to '%s'", stream->path);
1483

1484 1485
	return ret;
}
1486

1487
static int checkout_stream_close(git_writestream *s)
1488 1489 1490
{
	struct checkout_stream *stream = (struct checkout_stream *)s;
	assert(stream && stream->open);
1491

1492
	stream->open = 0;
1493
	return p_close(stream->fd);
1494
}
1495

1496
static void checkout_stream_free(git_writestream *s)
1497 1498
{
	GIT_UNUSED(s);
Ben Straub committed
1499 1500
}

1501
static int blob_content_to_file(
1502
	checkout_data *data,
1503
	struct stat *st,
1504 1505
	git_blob *blob,
	const char *path,
1506
	const char *hint_path,
1507
	mode_t entry_filemode)
1508
{
1509
	int flags = data->opts.file_open_flags;
1510 1511
	mode_t file_mode = data->opts.file_mode ?
		data->opts.file_mode : entry_filemode;
1512
	git_filter_options filter_opts = GIT_FILTER_OPTIONS_INIT;
1513 1514
	struct checkout_stream writer;
	mode_t mode;
1515
	git_filter_list *fl = NULL;
1516
	int fd;
1517
	int error = 0;
1518

1519 1520 1521
	if (hint_path == NULL)
		hint_path = path;

1522 1523 1524 1525 1526 1527 1528 1529 1530
	if ((error = mkpath2file(data, path, data->opts.dir_mode)) < 0)
		return error;

	if (flags <= 0)
		flags = O_CREAT | O_TRUNC | O_WRONLY;
	if (!(mode = file_mode))
		mode = GIT_FILEMODE_BLOB;

	if ((fd = p_open(path, flags, mode)) < 0) {
1531
		git_error_set(GIT_ERROR_OS, "could not open '%s' for writing", path);
1532 1533 1534
		return fd;
	}

1535
	filter_opts.attr_session = &data->attr_session;
1536
	filter_opts.temp_buf = &data->tmp;
1537

1538
	if (!data->opts.disable_filters &&
1539 1540
		(error = git_filter_list__load_ext(
			&fl, data->repo, blob, hint_path,
1541 1542
			GIT_FILTER_TO_WORKTREE, &filter_opts))) {
		p_close(fd);
1543
		return error;
1544
	}
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554

	/* setup the writer */
	memset(&writer, 0, sizeof(struct checkout_stream));
	writer.base.write = checkout_stream_write;
	writer.base.close = checkout_stream_close;
	writer.base.free = checkout_stream_free;
	writer.path = path;
	writer.fd = fd;
	writer.open = 1;

Leo Yang committed
1555
	error = git_filter_list_stream_blob(fl, blob, &writer.base);
1556

1557
	assert(writer.open == 0);
1558

1559
	git_filter_list_free(fl);
1560

1561 1562
	if (error < 0)
		return error;
1563

1564 1565 1566 1567
	if (st) {
		data->perfdata.stat_calls++;

		if ((error = p_stat(path, st)) < 0) {
1568
			git_error_set(GIT_ERROR_OS, "failed to stat '%s'", path);
1569 1570 1571 1572 1573 1574 1575
			return error;
		}

		st->st_mode = entry_filemode;
	}

	return 0;
1576 1577
}

1578
static int blob_content_to_link(
1579
	checkout_data *data,
1580 1581
	struct stat *st,
	git_blob *blob,
1582
	const char *path)
1583 1584 1585
{
	git_buf linktarget = GIT_BUF_INIT;
	int error;
1586

1587
	if ((error = mkpath2file(data, path, data->opts.dir_mode)) < 0)
Linquize committed
1588
		return error;
1589

1590 1591
	if ((error = git_blob__getbuf(&linktarget, blob)) < 0)
		return error;
1592

1593
	if (data->can_symlink) {
1594
		if ((error = p_symlink(git_buf_cstr(&linktarget), path)) < 0)
1595
			git_error_set(GIT_ERROR_OS, "could not create symlink %s", path);
1596
	} else {
1597
		error = git_futils_fake_symlink(git_buf_cstr(&linktarget), path);
1598 1599 1600
	}

	if (!error) {
1601 1602
		data->perfdata.stat_calls++;

1603
		if ((error = p_lstat(path, st)) < 0)
1604
			git_error_set(GIT_ERROR_CHECKOUT, "could not stat symlink %s", path);
1605 1606 1607

		st->st_mode = GIT_FILEMODE_LINK;
	}
1608

1609
	git_buf_dispose(&linktarget);
1610 1611

	return error;
1612 1613
}

1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
static int checkout_update_index(
	checkout_data *data,
	const git_diff_file *file,
	struct stat *st)
{
	git_index_entry entry;

	if (!data->index)
		return 0;

	memset(&entry, 0, sizeof(entry));
	entry.path = (char *)file->path; /* cast to prevent warning */
1626
	git_index_entry__init_from_stat(&entry, st, true);
1627
	git_oid_cpy(&entry.id, &file->id);
1628 1629 1630 1631

	return git_index_add(data->index, &entry);
}

1632 1633 1634 1635
static int checkout_submodule_update_index(
	checkout_data *data,
	const git_diff_file *file)
{
1636
	git_buf *fullpath;
1637 1638 1639 1640 1641 1642
	struct stat st;

	/* update the index unless prevented */
	if ((data->strategy & GIT_CHECKOUT_DONT_UPDATE_INDEX) != 0)
		return 0;

1643
	if (checkout_target_fullpath(&fullpath, data, file->path) < 0)
1644 1645
		return -1;

1646
	data->perfdata.stat_calls++;
1647
	if (p_stat(fullpath->ptr, &st) < 0) {
1648 1649
		git_error_set(
			GIT_ERROR_CHECKOUT, "could not stat submodule %s\n", file->path);
1650 1651 1652 1653 1654 1655 1656 1657
		return GIT_ENOTFOUND;
	}

	st.st_mode = GIT_FILEMODE_COMMIT;

	return checkout_update_index(data, file, &st);
}

1658
static int checkout_submodule(
1659
	checkout_data *data,
1660 1661
	const git_diff_file *file)
{
1662
	bool remove_existing = should_remove_existing(data);
1663 1664
	int error = 0;

1665
	/* Until submodules are supported, UPDATE_ONLY means do nothing here */
1666
	if ((data->strategy & GIT_CHECKOUT_UPDATE_ONLY) != 0)
1667 1668
		return 0;

1669 1670
	if ((error = checkout_mkdir(
			data,
1671 1672
			file->path, data->opts.target_directory, data->opts.dir_mode,
			remove_existing ? MKDIR_REMOVE_EXISTING : MKDIR_NORMAL)) < 0)
1673
		return error;
1674

1675
	if ((error = git_submodule_lookup(NULL, data->repo, file->path)) < 0) {
1676 1677 1678 1679
		/* I've observed repos with submodules in the tree that do not
		 * have a .gitmodules - core Git just makes an empty directory
		 */
		if (error == GIT_ENOTFOUND) {
1680
			git_error_clear();
1681 1682 1683
			return checkout_submodule_update_index(data, file);
		}

1684
		return error;
1685
	}
1686

1687
	/* TODO: Support checkout_strategy options.  Two circumstances:
1688 1689 1690 1691
	 * 1 - submodule already checked out, but we need to move the HEAD
	 *     to the new OID, or
	 * 2 - submodule not checked out and we should recursively check it out
	 *
1692 1693
	 * Checkout will not execute a pull on the submodule, but a clone
	 * command should probably be able to.  Do we need a submodule callback?
1694 1695
	 */

1696
	return checkout_submodule_update_index(data, file);
1697 1698
}

1699
static void report_progress(
1700
	checkout_data *data,
1701
	const char *path)
1702
{
1703 1704
	if (data->opts.progress_cb)
		data->opts.progress_cb(
1705
			path, data->completed_steps, data->total_steps,
1706
			data->opts.progress_payload);
1707 1708
}

1709 1710
static int checkout_safe_for_update_only(
	checkout_data *data, const char *path, mode_t expected_mode)
1711 1712 1713
{
	struct stat st;

1714 1715
	data->perfdata.stat_calls++;

1716 1717 1718 1719 1720 1721
	if (p_lstat(path, &st) < 0) {
		/* if doesn't exist, then no error and no update */
		if (errno == ENOENT || errno == ENOTDIR)
			return 0;

		/* otherwise, stat error and no update */
1722
		git_error_set(GIT_ERROR_OS, "failed to stat '%s'", path);
1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
		return -1;
	}

	/* only safe for update if this is the same type of file */
	if ((st.st_mode & ~0777) == (expected_mode & ~0777))
		return 1;

	return 0;
}

1733
static int checkout_write_content(
1734
	checkout_data *data,
1735 1736 1737 1738 1739
	const git_oid *oid,
	const char *full_path,
	const char *hint_path,
	unsigned int mode,
	struct stat *st)
1740
{
1741
	int error = 0;
1742
	git_blob *blob;
1743

1744
	if ((error = git_blob_lookup(&blob, data->repo, oid)) < 0)
1745 1746
		return error;

1747
	if (S_ISLNK(mode))
1748
		error = blob_content_to_link(data, st, blob, full_path);
1749
	else
1750
		error = blob_content_to_file(data, st, blob, full_path, hint_path, mode);
1751 1752 1753

	git_blob_free(blob);

1754 1755 1756 1757 1758 1759 1760
	/* if we try to create the blob and an existing directory blocks it from
	 * being written, then there must have been a typechange conflict in a
	 * parent directory - suppress the error and try to continue.
	 */
	if ((data->strategy & GIT_CHECKOUT_ALLOW_CONFLICTS) != 0 &&
		(error == GIT_ENOTFOUND || error == GIT_EEXISTS))
	{
1761
		git_error_clear();
1762 1763 1764
		error = 0;
	}

1765 1766 1767 1768 1769 1770 1771
	return error;
}

static int checkout_blob(
	checkout_data *data,
	const git_diff_file *file)
{
1772
	git_buf *fullpath;
1773
	struct stat st;
1774
	int error = 0;
1775

1776
	if (checkout_target_fullpath(&fullpath, data, file->path) < 0)
1777 1778 1779
		return -1;

	if ((data->strategy & GIT_CHECKOUT_UPDATE_ONLY) != 0) {
1780
		int rval = checkout_safe_for_update_only(
1781 1782
			data, fullpath->ptr, file->mode);

1783 1784 1785 1786
		if (rval <= 0)
			return rval;
	}

1787
	error = checkout_write_content(
1788
		data, &file->id, fullpath->ptr, NULL, file->mode, &st);
1789

1790 1791 1792 1793
	/* update the index unless prevented */
	if (!error && (data->strategy & GIT_CHECKOUT_DONT_UPDATE_INDEX) == 0)
		error = checkout_update_index(data, file, &st);

1794 1795 1796 1797
	/* update the submodule data if this was a new .gitmodules file */
	if (!error && strcmp(file->path, ".gitmodules") == 0)
		data->reload_submodules = true;

1798 1799 1800
	return error;
}

1801 1802
static int checkout_remove_the_old(
	unsigned int *actions,
1803
	checkout_data *data)
1804
{
1805
	int error = 0;
1806
	git_diff_delta *delta;
1807
	const char *str;
1808
	size_t i;
1809
	git_buf *fullpath;
1810 1811
	uint32_t flg = GIT_RMDIR_EMPTY_PARENTS |
		GIT_RMDIR_REMOVE_FILES | GIT_RMDIR_REMOVE_BLOCKERS;
1812

1813 1814 1815
	if (data->opts.checkout_strategy & GIT_CHECKOUT_SKIP_LOCKED_DIRECTORIES)
		flg |= GIT_RMDIR_SKIP_NONEMPTY;

1816 1817
	if (checkout_target_fullpath(&fullpath, data, NULL) < 0)
		return -1;
1818

1819
	git_vector_foreach(&data->diff->deltas, i, delta) {
1820
		if (actions[i] & CHECKOUT_ACTION__REMOVE) {
1821 1822 1823
			error = git_futils_rmdir_r(
				delta->old_file.path, fullpath->ptr, flg);

1824
			if (error < 0)
1825 1826 1827
				return error;

			data->completed_steps++;
1828
			report_progress(data, delta->old_file.path);
1829 1830 1831 1832 1833 1834 1835

			if ((actions[i] & CHECKOUT_ACTION__UPDATE_BLOB) == 0 &&
				(data->strategy & GIT_CHECKOUT_DONT_UPDATE_INDEX) == 0 &&
				data->index != NULL)
			{
				(void)git_index_remove(data->index, delta->old_file.path, 0);
			}
1836 1837 1838
		}
	}

1839
	git_vector_foreach(&data->removes, i, str) {
1840
		error = git_futils_rmdir_r(str, fullpath->ptr, flg);
1841 1842 1843 1844
		if (error < 0)
			return error;

		data->completed_steps++;
1845
		report_progress(data, str);
1846 1847 1848 1849

		if ((data->strategy & GIT_CHECKOUT_DONT_UPDATE_INDEX) == 0 &&
			data->index != NULL)
		{
1850 1851 1852 1853
			if (str[strlen(str) - 1] == '/')
				(void)git_index_remove_directory(data->index, str, 0);
			else
				(void)git_index_remove(data->index, str, 0);
1854
		}
1855 1856 1857 1858 1859
	}

	return 0;
}

1860 1861
static int checkout_create_the_new(
	unsigned int *actions,
1862
	checkout_data *data)
1863
{
1864
	int error = 0;
1865 1866 1867
	git_diff_delta *delta;
	size_t i;

1868
	git_vector_foreach(&data->diff->deltas, i, delta) {
1869 1870
		if (actions[i] & CHECKOUT_ACTION__UPDATE_BLOB && !S_ISLNK(delta->new_file.mode)) {
			if ((error = checkout_blob(data, &delta->new_file)) < 0)
1871
				return error;
1872 1873 1874 1875
			data->completed_steps++;
			report_progress(data, delta->new_file.path);
		}
	}
1876

1877 1878 1879 1880
	git_vector_foreach(&data->diff->deltas, i, delta) {
		if (actions[i] & CHECKOUT_ACTION__UPDATE_BLOB && S_ISLNK(delta->new_file.mode)) {
			if ((error = checkout_blob(data, &delta->new_file)) < 0)
				return error;
1881
			data->completed_steps++;
1882
			report_progress(data, delta->new_file.path);
1883 1884 1885 1886 1887 1888 1889 1890
		}
	}

	return 0;
}

static int checkout_create_submodules(
	unsigned int *actions,
1891
	checkout_data *data)
1892 1893 1894 1895
{
	git_diff_delta *delta;
	size_t i;

1896
	git_vector_foreach(&data->diff->deltas, i, delta) {
1897
		if (actions[i] & CHECKOUT_ACTION__UPDATE_SUBMODULE) {
1898
			int error = checkout_submodule(data, &delta->new_file);
1899 1900 1901 1902
			if (error < 0)
				return error;

			data->completed_steps++;
1903
			report_progress(data, delta->new_file.path);
1904 1905 1906
		}
	}

1907
	return 0;
1908 1909
}

1910 1911 1912 1913 1914 1915 1916
static int checkout_lookup_head_tree(git_tree **out, git_repository *repo)
{
	int error = 0;
	git_reference *ref = NULL;
	git_object *head;

	if (!(error = git_repository_head(&ref, repo)) &&
1917
		!(error = git_reference_peel(&head, ref, GIT_OBJECT_TREE)))
1918 1919 1920 1921 1922 1923 1924
		*out = (git_tree *)head;

	git_reference_free(ref);

	return error;
}

1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961

static int conflict_entry_name(
	git_buf *out,
	const char *side_name,
	const char *filename)
{
	if (git_buf_puts(out, side_name) < 0 ||
		git_buf_putc(out, ':') < 0 ||
		git_buf_puts(out, filename) < 0)
		return -1;

	return 0;
}

static int checkout_path_suffixed(git_buf *path, const char *suffix)
{
	size_t path_len;
	int i = 0, error = 0;

	if ((error = git_buf_putc(path, '~')) < 0 || (error = git_buf_puts(path, suffix)) < 0)
		return -1;

	path_len = git_buf_len(path);

	while (git_path_exists(git_buf_cstr(path)) && i < INT_MAX) {
		git_buf_truncate(path, path_len);

		if ((error = git_buf_putc(path, '_')) < 0 ||
			(error = git_buf_printf(path, "%d", i)) < 0)
			return error;

		i++;
	}

	if (i == INT_MAX) {
		git_buf_truncate(path, path_len);

1962
		git_error_set(GIT_ERROR_CHECKOUT, "could not write '%s': working directory file exists", path->ptr);
1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974
		return GIT_EEXISTS;
	}

	return 0;
}

static int checkout_write_entry(
	checkout_data *data,
	checkout_conflictdata *conflict,
	const git_index_entry *side)
{
	const char *hint_path = NULL, *suffix;
1975
	git_buf *fullpath;
1976 1977 1978 1979 1980
	struct stat st;
	int error;

	assert (side == conflict->ours || side == conflict->theirs);

1981
	if (checkout_target_fullpath(&fullpath, data, side->path) < 0)
1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994
		return -1;

	if ((conflict->name_collision || conflict->directoryfile) &&
		(data->strategy & GIT_CHECKOUT_USE_OURS) == 0 &&
		(data->strategy & GIT_CHECKOUT_USE_THEIRS) == 0) {

		if (side == conflict->ours)
			suffix = data->opts.our_label ? data->opts.our_label :
				"ours";
		else
			suffix = data->opts.their_label ? data->opts.their_label :
				"theirs";

1995
		if (checkout_path_suffixed(fullpath, suffix) < 0)
1996 1997 1998 1999 2000 2001
			return -1;

		hint_path = side->path;
	}

	if ((data->strategy & GIT_CHECKOUT_UPDATE_ONLY) != 0 &&
2002
		(error = checkout_safe_for_update_only(data, fullpath->ptr, side->mode)) <= 0)
2003 2004
		return error;

2005 2006 2007 2008 2009
	if (!S_ISGITLINK(side->mode))
		return checkout_write_content(data,
					      &side->id, fullpath->ptr, hint_path, side->mode, &st);

	return 0;
2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055
}

static int checkout_write_entries(
	checkout_data *data,
	checkout_conflictdata *conflict)
{
	int error = 0;

	if ((error = checkout_write_entry(data, conflict, conflict->ours)) >= 0)
		error = checkout_write_entry(data, conflict, conflict->theirs);

	return error;
}

static int checkout_merge_path(
	git_buf *out,
	checkout_data *data,
	checkout_conflictdata *conflict,
	git_merge_file_result *result)
{
	const char *our_label_raw, *their_label_raw, *suffix;
	int error = 0;

	if ((error = git_buf_joinpath(out, git_repository_workdir(data->repo), result->path)) < 0)
		return error;

	/* Most conflicts simply use the filename in the index */
	if (!conflict->name_collision)
		return 0;

	/* Rename 2->1 conflicts need the branch name appended */
	our_label_raw = data->opts.our_label ? data->opts.our_label : "ours";
	their_label_raw = data->opts.their_label ? data->opts.their_label : "theirs";
	suffix = strcmp(result->path, conflict->ours->path) == 0 ? our_label_raw : their_label_raw;

	if ((error = checkout_path_suffixed(out, suffix)) < 0)
		return error;

	return 0;
}

static int checkout_write_merge(
	checkout_data *data,
	checkout_conflictdata *conflict)
{
	git_buf our_label = GIT_BUF_INIT, their_label = GIT_BUF_INIT,
2056 2057
		path_suffixed = GIT_BUF_INIT, path_workdir = GIT_BUF_INIT,
		in_data = GIT_BUF_INIT, out_data = GIT_BUF_INIT;
2058 2059
	git_merge_file_options opts = GIT_MERGE_FILE_OPTIONS_INIT;
	git_merge_file_result result = {0};
2060
	git_filebuf output = GIT_FILEBUF_INIT;
2061
	git_filter_list *fl = NULL;
2062
	git_filter_options filter_opts = GIT_FILTER_OPTIONS_INIT;
2063 2064
	int error = 0;

2065
	if (data->opts.checkout_strategy & GIT_CHECKOUT_CONFLICT_STYLE_DIFF3)
2066
		opts.flags |= GIT_MERGE_FILE_STYLE_DIFF3;
2067

2068 2069 2070 2071 2072 2073
	opts.ancestor_label = data->opts.ancestor_label ?
		data->opts.ancestor_label : "ancestor";
	opts.our_label = data->opts.our_label ?
		data->opts.our_label : "ours";
	opts.their_label = data->opts.their_label ?
		data->opts.their_label : "theirs";
2074 2075 2076 2077 2078 2079 2080 2081

	/* If all the paths are identical, decorate the diff3 file with the branch
	 * names.  Otherwise, append branch_name:path.
	 */
	if (conflict->ours && conflict->theirs &&
		strcmp(conflict->ours->path, conflict->theirs->path) != 0) {

		if ((error = conflict_entry_name(
2082
			&our_label, opts.our_label, conflict->ours->path)) < 0 ||
2083
			(error = conflict_entry_name(
2084
			&their_label, opts.their_label, conflict->theirs->path)) < 0)
2085 2086
			goto done;

2087 2088
		opts.our_label = git_buf_cstr(&our_label);
		opts.their_label = git_buf_cstr(&their_label);
2089 2090
	}

2091 2092
	if ((error = git_merge_file_from_index(&result, data->repo,
		conflict->ancestor, conflict->ours, conflict->theirs, &opts)) < 0)
2093 2094 2095
		goto done;

	if (result.path == NULL || result.mode == 0) {
2096
		git_error_set(GIT_ERROR_CHECKOUT, "could not merge contents of file");
2097
		error = GIT_ECONFLICT;
2098 2099 2100 2101 2102 2103 2104
		goto done;
	}

	if ((error = checkout_merge_path(&path_workdir, data, conflict, &result)) < 0)
		goto done;

	if ((data->strategy & GIT_CHECKOUT_UPDATE_ONLY) != 0 &&
2105
		(error = checkout_safe_for_update_only(data, git_buf_cstr(&path_workdir), result.mode)) <= 0)
2106 2107
		goto done;

2108
	if (!data->opts.disable_filters) {
2109 2110 2111
		in_data.ptr = (char *)result.ptr;
		in_data.size = result.len;

2112
		filter_opts.attr_session = &data->attr_session;
2113
		filter_opts.temp_buf = &data->tmp;
2114 2115 2116 2117

		if ((error = git_filter_list__load_ext(
				&fl, data->repo, NULL, git_buf_cstr(&path_workdir),
				GIT_FILTER_TO_WORKTREE, &filter_opts)) < 0 ||
2118 2119
			(error = git_filter_list_apply_to_data(&out_data, fl, &in_data)) < 0)
			goto done;
2120 2121 2122 2123
	} else {
		out_data.ptr = (char *)result.ptr;
		out_data.size = result.len;
	}
2124

2125
	if ((error = mkpath2file(data, path_workdir.ptr, data->opts.dir_mode)) < 0 ||
2126 2127
		(error = git_filebuf_open(&output, git_buf_cstr(&path_workdir), GIT_FILEBUF_DO_NOT_BUFFER, result.mode)) < 0 ||
		(error = git_filebuf_write(&output, out_data.ptr, out_data.size)) < 0 ||
2128
		(error = git_filebuf_commit(&output)) < 0)
2129 2130 2131
		goto done;

done:
2132 2133
	git_filter_list_free(fl);

2134 2135 2136
	git_buf_dispose(&out_data);
	git_buf_dispose(&our_label);
	git_buf_dispose(&their_label);
2137 2138

	git_merge_file_result_free(&result);
2139 2140
	git_buf_dispose(&path_workdir);
	git_buf_dispose(&path_suffixed);
2141 2142 2143 2144

	return error;
}

2145 2146 2147 2148 2149 2150 2151
static int checkout_conflict_add(
	checkout_data *data,
	const git_index_entry *conflict)
{
	int error = git_index_remove(data->index, conflict->path, 0);

	if (error == GIT_ENOTFOUND)
2152
		git_error_clear();
2153 2154 2155 2156 2157 2158
	else if (error < 0)
		return error;

	return git_index_add(data->index, conflict);
}

2159 2160 2161 2162 2163 2164 2165
static int checkout_conflict_update_index(
	checkout_data *data,
	checkout_conflictdata *conflict)
{
	int error = 0;

	if (conflict->ancestor)
2166
		error = checkout_conflict_add(data, conflict->ancestor);
2167 2168

	if (!error && conflict->ours)
2169
		error = checkout_conflict_add(data, conflict->ours);
2170 2171

	if (!error && conflict->theirs)
2172
		error = checkout_conflict_add(data, conflict->theirs);
2173 2174 2175 2176

	return error;
}

2177 2178 2179 2180 2181 2182
static int checkout_create_conflicts(checkout_data *data)
{
	checkout_conflictdata *conflict;
	size_t i;
	int error = 0;

2183
	git_vector_foreach(&data->update_conflicts, i, conflict) {
2184

2185 2186 2187 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 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227
		/* Both deleted: nothing to do */
		if (conflict->ours == NULL && conflict->theirs == NULL)
			error = 0;

		else if ((data->strategy & GIT_CHECKOUT_USE_OURS) &&
			conflict->ours)
			error = checkout_write_entry(data, conflict, conflict->ours);
		else if ((data->strategy & GIT_CHECKOUT_USE_THEIRS) &&
			conflict->theirs)
			error = checkout_write_entry(data, conflict, conflict->theirs);

		/* Ignore the other side of name collisions. */
		else if ((data->strategy & GIT_CHECKOUT_USE_OURS) &&
			!conflict->ours && conflict->name_collision)
			error = 0;
		else if ((data->strategy & GIT_CHECKOUT_USE_THEIRS) &&
			!conflict->theirs && conflict->name_collision)
			error = 0;

		/* For modify/delete, name collisions and d/f conflicts, write
		 * the file (potentially with the name mangled.
		 */
		else if (conflict->ours != NULL && conflict->theirs == NULL)
			error = checkout_write_entry(data, conflict, conflict->ours);
		else if (conflict->ours == NULL && conflict->theirs != NULL)
			error = checkout_write_entry(data, conflict, conflict->theirs);

		/* Add/add conflicts and rename 1->2 conflicts, write the
		 * ours/theirs sides (potentially name mangled).
		 */
		else if (conflict->one_to_two)
			error = checkout_write_entries(data, conflict);

		/* If all sides are links, write the ours side */
		else if (S_ISLNK(conflict->ours->mode) &&
			S_ISLNK(conflict->theirs->mode))
			error = checkout_write_entry(data, conflict, conflict->ours);
		/* Link/file conflicts, write the file side */
		else if (S_ISLNK(conflict->ours->mode))
			error = checkout_write_entry(data, conflict, conflict->theirs);
		else if (S_ISLNK(conflict->theirs->mode))
			error = checkout_write_entry(data, conflict, conflict->ours);

Edward Thomson committed
2228 2229 2230 2231
		/* If any side is a gitlink, do nothing. */
		else if (conflict->submodule)
			error = 0;

2232 2233 2234 2235 2236
		/* If any side is binary, write the ours side */
		else if (conflict->binary)
			error = checkout_write_entry(data, conflict, conflict->ours);

		else if (!error)
2237 2238
			error = checkout_write_merge(data, conflict);

2239 2240 2241 2242 2243 2244
		/* Update the index extensions (REUC and NAME) if we're checking
		 * out a different index. (Otherwise just leave them there.)
		 */
		if (!error && (data->strategy & GIT_CHECKOUT_DONT_UPDATE_INDEX) == 0)
			error = checkout_conflict_update_index(data, conflict);

2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256
		if (error)
			break;

		data->completed_steps++;
		report_progress(data,
			conflict->ours ? conflict->ours->path :
			(conflict->theirs ? conflict->theirs->path : conflict->ancestor->path));
	}

	return error;
}

2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271
static int checkout_remove_conflicts(checkout_data *data)
{
	const char *conflict;
	size_t i;

	git_vector_foreach(&data->remove_conflicts, i, conflict) {
		if (git_index_conflict_remove(data->index, conflict) < 0)
			return -1;

		data->completed_steps++;
	}

	return 0;
}

2272 2273 2274 2275 2276 2277 2278 2279 2280 2281
static int checkout_extensions_update_index(checkout_data *data)
{
	const git_index_reuc_entry *reuc_entry;
	const git_index_name_entry *name_entry;
	size_t i;
	int error = 0;

	if ((data->strategy & GIT_CHECKOUT_UPDATE_ONLY) != 0)
		return 0;

2282 2283
	if (data->update_reuc) {
		git_vector_foreach(data->update_reuc, i, reuc_entry) {
2284 2285 2286 2287 2288 2289 2290 2291
			if ((error = git_index_reuc_add(data->index, reuc_entry->path,
				reuc_entry->mode[0], &reuc_entry->oid[0],
				reuc_entry->mode[1], &reuc_entry->oid[1],
				reuc_entry->mode[2], &reuc_entry->oid[2])) < 0)
				goto done;
		}
	}

2292 2293
	if (data->update_names) {
		git_vector_foreach(data->update_names, i, name_entry) {
2294 2295 2296 2297 2298 2299 2300 2301 2302
			if ((error = git_index_name_add(data->index, name_entry->ancestor,
				name_entry->ours, name_entry->theirs)) < 0)
				goto done;
		}
	}

done:
	return error;
}
2303

2304 2305 2306 2307 2308 2309 2310 2311 2312 2313
static void checkout_data_clear(checkout_data *data)
{
	if (data->opts_free_baseline) {
		git_tree_free(data->opts.baseline);
		data->opts.baseline = NULL;
	}

	git_vector_free(&data->removes);
	git_pool_clear(&data->pool);

2314 2315
	git_vector_free_deep(&data->remove_conflicts);
	git_vector_free_deep(&data->update_conflicts);
2316

2317 2318 2319
	git__free(data->pfx);
	data->pfx = NULL;

2320 2321
	git_buf_dispose(&data->target_path);
	git_buf_dispose(&data->tmp);
2322 2323 2324

	git_index_free(data->index);
	data->index = NULL;
2325

2326
	git_strmap_free(data->mkdir_map);
2327
	data->mkdir_map = NULL;
2328

2329
	git_attr_session__free(&data->attr_session);
2330 2331 2332 2333
}

static int checkout_data_init(
	checkout_data *data,
2334
	git_iterator *target,
2335
	const git_checkout_options *proposed)
2336
{
2337
	int error = 0;
2338
	git_repository *repo = git_iterator_owner(target);
2339

2340 2341 2342
	memset(data, 0, sizeof(*data));

	if (!repo) {
2343
		git_error_set(GIT_ERROR_CHECKOUT, "cannot checkout nothing");
2344
		return -1;
2345
	}
2346

2347 2348
	if ((!proposed || !proposed->target_directory) &&
		(error = git_repository__ensure_not_bare(repo, "checkout")) < 0)
2349
		return error;
2350

2351
	data->repo = repo;
2352
	data->target = target;
2353

2354
	GIT_ERROR_CHECK_VERSION(
2355
		proposed, GIT_CHECKOUT_OPTIONS_VERSION, "git_checkout_options");
2356 2357

	if (!proposed)
2358
		GIT_INIT_STRUCTURE(&data->opts, GIT_CHECKOUT_OPTIONS_VERSION);
2359
	else
2360
		memmove(&data->opts, proposed, sizeof(git_checkout_options));
2361

2362 2363 2364
	if (!data->opts.target_directory)
		data->opts.target_directory = git_repository_workdir(repo);
	else if (!git_path_isdir(data->opts.target_directory) &&
2365 2366 2367
			 (error = checkout_mkdir(data,
				data->opts.target_directory, NULL,
				GIT_DIR_MODE, GIT_MKDIR_VERIFY_DIR)) < 0)
2368 2369
		goto cleanup;

2370 2371 2372
	if ((error = git_repository_index(&data->index, data->repo)) < 0)
		goto cleanup;

2373 2374
	/* refresh config and index content unless NO_REFRESH is given */
	if ((data->opts.checkout_strategy & GIT_CHECKOUT_NO_REFRESH) == 0) {
2375 2376
		git_config *cfg;

2377
		if ((error = git_repository_config__weakptr(&cfg, repo)) < 0)
2378 2379
			goto cleanup;

2380 2381 2382
		/* Reload the repository index (unless we're checking out the
		 * index; then it has the changes we're trying to check out
		 * and those should not be overwritten.)
2383
		 */
2384
		if (data->index != git_iterator_index(target)) {
2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396
			if (data->opts.checkout_strategy & GIT_CHECKOUT_FORCE) {
				/* When forcing, we can blindly re-read the index */
				if ((error = git_index_read(data->index, false)) < 0)
					goto cleanup;
			} else {
				/*
				 * When not being forced, we need to check for unresolved
				 * conflicts and unsaved changes in the index before
				 * proceeding.
				 */
				if (git_index_has_conflicts(data->index)) {
					error = GIT_ECONFLICT;
2397
					git_error_set(GIT_ERROR_CHECKOUT,
2398 2399 2400 2401 2402 2403
						"unresolved conflicts exist in the index");
					goto cleanup;
				}

				if ((error = git_index_read_safely(data->index)) < 0)
					goto cleanup;
2404 2405
			}

2406
			/* clean conflict data in the current index */
2407
			git_index_name_clear(data->index);
Edward Thomson committed
2408
			git_index_reuc_clear(data->index);
2409 2410
		}
	}
2411

2412 2413 2414 2415 2416
	/* if you are forcing, allow all safe updates, plus recreate missing */
	if ((data->opts.checkout_strategy & GIT_CHECKOUT_FORCE) != 0)
		data->opts.checkout_strategy |= GIT_CHECKOUT_SAFE |
			GIT_CHECKOUT_RECREATE_MISSING;

2417 2418 2419 2420 2421
	/* if the repository does not actually have an index file, then this
	 * is an initial checkout (perhaps from clone), so we allow safe updates
	 */
	if (!data->index->on_disk &&
		(data->opts.checkout_strategy & GIT_CHECKOUT_SAFE) != 0)
2422
		data->opts.checkout_strategy |= GIT_CHECKOUT_RECREATE_MISSING;
2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435

	data->strategy = data->opts.checkout_strategy;

	/* opts->disable_filters is false by default */

	if (!data->opts.dir_mode)
		data->opts.dir_mode = GIT_DIR_MODE;

	if (!data->opts.file_open_flags)
		data->opts.file_open_flags = O_CREAT | O_TRUNC | O_WRONLY;

	data->pfx = git_pathspec_prefix(&data->opts.paths);

2436 2437
	if ((error = git_repository__configmap_lookup(
			 &data->can_symlink, repo, GIT_CONFIGMAP_SYMLINKS)) < 0)
2438
		goto cleanup;
2439

2440 2441
	if ((error = git_repository__configmap_lookup(
			 &data->respect_filemode, repo, GIT_CONFIGMAP_FILEMODE)) < 0)
2442 2443
		goto cleanup;

2444
	if (!data->opts.baseline && !data->opts.baseline_index) {
2445
		data->opts_free_baseline = true;
2446
		error = 0;
2447

2448 2449 2450 2451 2452
		/* if we don't have an index, this is an initial checkout and
		 * should be against an empty baseline
		 */
		if (data->index->on_disk)
			error = checkout_lookup_head_tree(&data->opts.baseline, repo);
2453

2454
		if (error == GIT_EUNBORNBRANCH) {
2455
			error = 0;
2456
			git_error_clear();
2457 2458 2459
		}

		if (error < 0)
2460 2461 2462
			goto cleanup;
	}

2463 2464
	if ((data->opts.checkout_strategy &
		(GIT_CHECKOUT_CONFLICT_STYLE_MERGE | GIT_CHECKOUT_CONFLICT_STYLE_DIFF3)) == 0) {
2465
		git_config_entry *conflict_style = NULL;
2466 2467 2468
		git_config *cfg = NULL;

		if ((error = git_repository_config__weakptr(&cfg, repo)) < 0 ||
2469
			(error = git_config_get_entry(&conflict_style, cfg, "merge.conflictstyle")) < 0 ||
2470 2471 2472 2473
			error == GIT_ENOTFOUND)
			;
		else if (error)
			goto cleanup;
2474
		else if (strcmp(conflict_style->value, "merge") == 0)
2475
			data->opts.checkout_strategy |= GIT_CHECKOUT_CONFLICT_STYLE_MERGE;
2476
		else if (strcmp(conflict_style->value, "diff3") == 0)
2477 2478
			data->opts.checkout_strategy |= GIT_CHECKOUT_CONFLICT_STYLE_DIFF3;
		else {
2479
			git_error_set(GIT_ERROR_CHECKOUT, "unknown style '%s' given for 'merge.conflictstyle'",
2480
				conflict_style->value);
2481
			error = -1;
2482
			git_config_entry_free(conflict_style);
2483 2484
			goto cleanup;
		}
2485
		git_config_entry_free(conflict_style);
2486 2487
	}

2488 2489
	if ((error = git_pool_init(&data->pool, 1)) < 0 ||
	    (error = git_vector_init(&data->removes, 0, git__strcmp_cb)) < 0 ||
2490 2491 2492 2493 2494
	    (error = git_vector_init(&data->remove_conflicts, 0, NULL)) < 0 ||
	    (error = git_vector_init(&data->update_conflicts, 0, NULL)) < 0 ||
	    (error = git_buf_puts(&data->target_path, data->opts.target_directory)) < 0 ||
	    (error = git_path_to_dir(&data->target_path)) < 0 ||
	    (error = git_strmap_new(&data->mkdir_map)) < 0)
2495 2496
		goto cleanup;

2497
	data->target_len = git_buf_len(&data->target_path);
2498

2499 2500
	git_attr_session__init(&data->attr_session, data->repo);

2501 2502 2503
cleanup:
	if (error < 0)
		checkout_data_clear(data);
2504 2505 2506 2507

	return error;
}

2508 2509 2510
#define CHECKOUT_INDEX_DONT_WRITE_MASK \
	(GIT_CHECKOUT_DONT_UPDATE_INDEX | GIT_CHECKOUT_DONT_WRITE_INDEX)

2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521
GIT_INLINE(void) setup_pathspecs(
	git_iterator_options *iter_opts,
	const git_checkout_options *checkout_opts)
{
	if (checkout_opts &&
		(checkout_opts->checkout_strategy & GIT_CHECKOUT_DISABLE_PATHSPEC_MATCH)) {
		iter_opts->pathlist.count = checkout_opts->paths.count;
		iter_opts->pathlist.strings = checkout_opts->paths.strings;
	}
}

2522 2523
int git_checkout_iterator(
	git_iterator *target,
2524
	git_index *index,
2525
	const git_checkout_options *opts)
2526 2527
{
	int error = 0;
2528
	git_iterator *baseline = NULL, *workdir = NULL;
2529 2530
	git_iterator_options baseline_opts = GIT_ITERATOR_OPTIONS_INIT,
		workdir_opts = GIT_ITERATOR_OPTIONS_INIT;
2531
	checkout_data data = {0};
2532
	git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT;
2533 2534
	uint32_t *actions = NULL;
	size_t *counts = NULL;
2535

2536
	/* initialize structures and options */
2537
	error = checkout_data_init(&data, target, opts);
2538 2539
	if (error < 0)
		return error;
Ben Straub committed
2540

2541 2542
	diff_opts.flags =
		GIT_DIFF_INCLUDE_UNMODIFIED |
2543
		GIT_DIFF_INCLUDE_UNREADABLE |
2544 2545 2546 2547 2548
		GIT_DIFF_INCLUDE_UNTRACKED |
		GIT_DIFF_RECURSE_UNTRACKED_DIRS | /* needed to match baseline */
		GIT_DIFF_INCLUDE_IGNORED |
		GIT_DIFF_INCLUDE_TYPECHANGE |
		GIT_DIFF_INCLUDE_TYPECHANGE_TREES |
2549 2550
		GIT_DIFF_SKIP_BINARY_CHECK |
		GIT_DIFF_INCLUDE_CASECHANGE;
2551 2552
	if (data.opts.checkout_strategy & GIT_CHECKOUT_DISABLE_PATHSPEC_MATCH)
		diff_opts.flags |= GIT_DIFF_DISABLE_PATHSPEC_MATCH;
2553 2554 2555 2556
	if (data.opts.paths.count > 0)
		diff_opts.pathspec = data.opts.paths;

	/* set up iterators */
2557

2558
	workdir_opts.flags = git_iterator_ignore_case(target) ?
2559
		GIT_ITERATOR_IGNORE_CASE : GIT_ITERATOR_DONT_IGNORE_CASE;
2560 2561 2562
	workdir_opts.flags |= GIT_ITERATOR_DONT_AUTOEXPAND;
	workdir_opts.start = data.pfx;
	workdir_opts.end = data.pfx;
2563

2564 2565
	setup_pathspecs(&workdir_opts, opts);

2566
	if ((error = git_iterator_reset_range(target, data.pfx, data.pfx)) < 0 ||
2567
		(error = git_iterator_for_workdir_ext(
2568
			&workdir, data.repo, data.opts.target_directory, index, NULL,
2569
			&workdir_opts)) < 0)
2570 2571
		goto cleanup;

2572 2573 2574 2575
	baseline_opts.flags = git_iterator_ignore_case(target) ?
		GIT_ITERATOR_IGNORE_CASE : GIT_ITERATOR_DONT_IGNORE_CASE;
	baseline_opts.start = data.pfx;
	baseline_opts.end = data.pfx;
2576 2577

	setup_pathspecs(&baseline_opts, opts);
2578

2579 2580
	if (data.opts.baseline_index) {
		if ((error = git_iterator_for_index(
2581 2582
				&baseline, git_index_owner(data.opts.baseline_index),
				data.opts.baseline_index, &baseline_opts)) < 0)
2583 2584 2585
			goto cleanup;
	} else {
		if ((error = git_iterator_for_tree(
2586
				&baseline, data.opts.baseline, &baseline_opts)) < 0)
2587 2588 2589
			goto cleanup;
	}

2590 2591
	/* Should not have case insensitivity mismatch */
	assert(git_iterator_ignore_case(workdir) == git_iterator_ignore_case(baseline));
2592

2593 2594
	/* Generate baseline-to-target diff which will include an entry for
	 * every possible update that might need to be made.
2595 2596
	 */
	if ((error = git_diff__from_iterators(
2597
			&data.diff, data.repo, baseline, target, &diff_opts)) < 0)
2598 2599
		goto cleanup;

2600
	/* Loop through diff (and working directory iterator) building a list of
2601 2602
	 * actions to be taken, plus look for conflicts and send notifications,
	 * then loop through conflicts.
2603
	 */
2604
	if ((error = checkout_get_actions(&actions, &counts, &data, workdir)) != 0)
2605 2606
		goto cleanup;

2607
	data.total_steps = counts[CHECKOUT_ACTION__REMOVE] +
2608
		counts[CHECKOUT_ACTION__REMOVE_CONFLICT] +
2609
		counts[CHECKOUT_ACTION__UPDATE_BLOB] +
2610 2611
		counts[CHECKOUT_ACTION__UPDATE_SUBMODULE] +
		counts[CHECKOUT_ACTION__UPDATE_CONFLICT];
2612

2613
	report_progress(&data, NULL); /* establish 0 baseline */
2614

2615 2616 2617
	/* To deal with some order dependencies, perform remaining checkout
	 * in three passes: removes, then update blobs, then update submodules.
	 */
2618
	if (counts[CHECKOUT_ACTION__REMOVE] > 0 &&
2619
		(error = checkout_remove_the_old(actions, &data)) < 0)
2620 2621
		goto cleanup;

2622 2623 2624 2625
	if (counts[CHECKOUT_ACTION__REMOVE_CONFLICT] > 0 &&
		(error = checkout_remove_conflicts(&data)) < 0)
		goto cleanup;

2626
	if (counts[CHECKOUT_ACTION__UPDATE_BLOB] > 0 &&
2627
		(error = checkout_create_the_new(actions, &data)) < 0)
2628 2629
		goto cleanup;

2630
	if (counts[CHECKOUT_ACTION__UPDATE_SUBMODULE] > 0 &&
2631
		(error = checkout_create_submodules(actions, &data)) < 0)
2632 2633
		goto cleanup;

2634
	if (counts[CHECKOUT_ACTION__UPDATE_CONFLICT] > 0 &&
2635
		(error = checkout_create_conflicts(&data)) < 0)
2636
		goto cleanup;
2637

2638
	if (data.index != git_iterator_index(target) &&
2639 2640 2641
		(error = checkout_extensions_update_index(&data)) < 0)
		goto cleanup;

2642
	assert(data.completed_steps == data.total_steps);
2643

2644 2645 2646
	if (data.opts.perfdata_cb)
		data.opts.perfdata_cb(&data.perfdata, data.opts.perfdata_payload);

2647
cleanup:
2648
	if (!error && data.index != NULL &&
2649
		(data.strategy & CHECKOUT_INDEX_DONT_WRITE_MASK) == 0)
2650 2651
		error = git_index_write(data.index);

2652
	git_diff_free(data.diff);
2653
	git_iterator_free(workdir);
2654
	git_iterator_free(baseline);
2655 2656
	git__free(actions);
	git__free(counts);
2657
	checkout_data_clear(&data);
2658 2659 2660 2661 2662 2663 2664

	return error;
}

int git_checkout_index(
	git_repository *repo,
	git_index *index,
2665
	const git_checkout_options *opts)
2666
{
2667
	git_iterator_options iter_opts = GIT_ITERATOR_OPTIONS_INIT;
2668
	int error, owned = 0;
2669
	git_iterator *index_i;
2670

2671
	if (!index && !repo) {
2672
		git_error_set(GIT_ERROR_CHECKOUT,
2673
			"must provide either repository or index to checkout");
2674 2675
		return -1;
	}
2676 2677 2678 2679

	if (index && repo &&
		git_index_owner(index) &&
		git_index_owner(index) != repo) {
2680
		git_error_set(GIT_ERROR_CHECKOUT,
2681
			"index to checkout does not match repository");
2682
		return -1;
2683 2684 2685
	} else if(index && repo && !git_index_owner(index)) {
		GIT_REFCOUNT_OWN(index, repo);
		owned = 1;
2686 2687 2688 2689
	}

	if (!repo)
		repo = git_index_owner(index);
2690 2691 2692

	if (!index && (error = git_repository_index__weakptr(&index, repo)) < 0)
		return error;
2693
	GIT_REFCOUNT_INC(index);
2694

2695 2696 2697
	setup_pathspecs(&iter_opts, opts);

	if (!(error = git_iterator_for_index(&index_i, repo, index, &iter_opts)))
2698
		error = git_checkout_iterator(index_i, index, opts);
2699

2700 2701 2702
	if (owned)
		GIT_REFCOUNT_OWN(index, NULL);

2703
	git_iterator_free(index_i);
2704
	git_index_free(index);
2705

2706 2707 2708 2709 2710
	return error;
}

int git_checkout_tree(
	git_repository *repo,
Vicent Marti committed
2711
	const git_object *treeish,
2712
	const git_checkout_options *opts)
2713
{
2714
	int error;
2715
	git_index *index;
2716 2717
	git_tree *tree = NULL;
	git_iterator *tree_i = NULL;
2718
	git_iterator_options iter_opts = GIT_ITERATOR_OPTIONS_INIT;
2719

2720
	if (!treeish && !repo) {
2721
		git_error_set(GIT_ERROR_CHECKOUT,
2722
			"must provide either repository or tree to checkout");
2723 2724 2725
		return -1;
	}
	if (treeish && repo && git_object_owner(treeish) != repo) {
2726
		git_error_set(GIT_ERROR_CHECKOUT,
2727
			"object to checkout does not match repository");
2728 2729 2730 2731 2732
		return -1;
	}

	if (!repo)
		repo = git_object_owner(treeish);
2733

2734
	if (treeish) {
2735
		if (git_object_peel((git_object **)&tree, treeish, GIT_OBJECT_TREE) < 0) {
2736 2737
			git_error_set(
				GIT_ERROR_CHECKOUT, "provided object cannot be peeled to a tree");
2738 2739 2740 2741 2742 2743
			return -1;
		}
	}
	else {
		if ((error = checkout_lookup_head_tree(&tree, repo)) < 0) {
			if (error != GIT_EUNBORNBRANCH)
2744 2745
				git_error_set(
					GIT_ERROR_CHECKOUT,
2746 2747 2748
					"HEAD could not be peeled to a tree and no treeish given");
			return error;
		}
2749 2750
	}

2751 2752 2753
	if ((error = git_repository_index(&index, repo)) < 0)
		return error;

2754
	setup_pathspecs(&iter_opts, opts);
2755 2756

	if (!(error = git_iterator_for_tree(&tree_i, tree, &iter_opts)))
2757
		error = git_checkout_iterator(tree_i, index, opts);
2758

2759
	git_iterator_free(tree_i);
2760
	git_index_free(index);
2761
	git_tree_free(tree);
2762

2763
	return error;
2764 2765
}

2766 2767
int git_checkout_head(
	git_repository *repo,
2768
	const git_checkout_options *opts)
2769
{
2770
	assert(repo);
2771
	return git_checkout_tree(repo, NULL, opts);
2772
}
2773

2774
int git_checkout_options_init(git_checkout_options *opts, unsigned int version)
2775
{
2776 2777 2778
	GIT_INIT_STRUCTURE_FROM_TEMPLATE(
		opts, version, git_checkout_options, GIT_CHECKOUT_OPTIONS_INIT);
	return 0;
2779
}
2780

2781
#ifndef GIT_DEPRECATE_HARD
2782 2783 2784 2785
int git_checkout_init_options(git_checkout_options *opts, unsigned int version)
{
	return git_checkout_options_init(opts, version);
}
2786
#endif