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

#include <assert.h>

10 11
#include "checkout.h"

12 13 14
#include "git2/repository.h"
#include "git2/refs.h"
#include "git2/tree.h"
15
#include "git2/blob.h"
16
#include "git2/config.h"
17
#include "git2/diff.h"
18
#include "git2/submodule.h"
Vicent Marti committed
19
#include "git2/sys/index.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 "pathspec.h"
28
#include "buf_text.h"
29
#include "merge_file.h"
30
#include "path.h"
31

32
/* See docs/checkout-internals.md for more information */
33

34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
enum {
	CHECKOUT_ACTION__NONE = 0,
	CHECKOUT_ACTION__REMOVE = 1,
	CHECKOUT_ACTION__UPDATE_BLOB = 2,
	CHECKOUT_ACTION__UPDATE_SUBMODULE = 4,
	CHECKOUT_ACTION__CONFLICT = 8,
	CHECKOUT_ACTION__UPDATE_CONFLICT = 16,
	CHECKOUT_ACTION__MAX = 16,
	CHECKOUT_ACTION__DEFER_REMOVE = 32,
	CHECKOUT_ACTION__REMOVE_AND_UPDATE =
		(CHECKOUT_ACTION__UPDATE_BLOB | CHECKOUT_ACTION__REMOVE),
};

typedef struct {
	git_repository *repo;
49
	git_diff *diff;
50
	git_checkout_options opts;
51 52 53 54 55 56 57 58
	bool opts_free_baseline;
	char *pfx;
	git_index *index;
	git_pool pool;
	git_vector removes;
	git_vector conflicts;
	git_buf path;
	size_t workdir_len;
59
	git_buf tmp;
60 61 62 63 64 65 66 67 68 69 70 71 72 73
	unsigned int strategy;
	int can_symlink;
	bool reload_submodules;
	size_t total_steps;
	size_t completed_steps;
} 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,
74
		one_to_two:1,
Edward Thomson committed
75 76
		binary:1,
		submodule:1;
77 78
} checkout_conflictdata;

79
static int checkout_notify(
80
	checkout_data *data,
81 82
	git_checkout_notify_t why,
	const git_diff_delta *delta,
83
	const git_index_entry *wditem)
84
{
85
	git_diff_file wdfile;
86
	const git_diff_file *baseline = NULL, *target = NULL, *workdir = NULL;
87
	const char *path = NULL;
88

89 90
	if (!data->opts.notify_cb ||
		(why & data->opts.notify_flags) == 0)
91 92
		return 0;

93 94
	if (wditem) {
		memset(&wdfile, 0, sizeof(wdfile));
95

96
		git_oid_cpy(&wdfile.id, &wditem->id);
97 98
		wdfile.path = wditem->path;
		wdfile.size = wditem->file_size;
99
		wdfile.flags = GIT_DIFF_FLAG_VALID_ID;
100
		wdfile.mode = wditem->mode;
101

102
		workdir = &wdfile;
103 104

		path = wditem->path;
105 106
	}

107
	if (delta) {
108 109 110 111 112
		switch (delta->status) {
		case GIT_DELTA_UNMODIFIED:
		case GIT_DELTA_MODIFIED:
		case GIT_DELTA_TYPECHANGE:
		default:
113 114
			baseline = &delta->old_file;
			target = &delta->new_file;
115 116 117 118
			break;
		case GIT_DELTA_ADDED:
		case GIT_DELTA_IGNORED:
		case GIT_DELTA_UNTRACKED:
119
			target = &delta->new_file;
120 121
			break;
		case GIT_DELTA_DELETED:
122
			baseline = &delta->old_file;
123 124
			break;
		}
125 126

		path = delta->old_file.path;
127 128
	}

129 130 131 132 133 134 135
	{
		int error = data->opts.notify_cb(
			why, path, baseline, target, workdir, data->opts.notify_payload);

		return giterr_set_after_callback_function(
			error, "git_checkout notification");
	}
136 137 138
}

static bool checkout_is_workdir_modified(
139
	checkout_data *data,
140 141
	const git_diff_file *baseitem,
	const git_index_entry *wditem)
142 143
{
	git_oid oid;
144
	const git_index_entry *ie;
145

146 147 148 149 150
	/* handle "modified" submodule */
	if (wditem->mode == GIT_FILEMODE_COMMIT) {
		git_submodule *sm;
		unsigned int sm_status = 0;
		const git_oid *sm_oid = NULL;
151
		bool rval = false;
152

153 154
		if (git_submodule_lookup(&sm, data->repo, wditem->path) < 0) {
			giterr_clear();
155
			return true;
156
		}
157

158 159 160 161 162 163 164
		if (git_submodule_status(&sm_status, sm) < 0 ||
			GIT_SUBMODULE_STATUS_IS_WD_DIRTY(sm_status))
			rval = true;
		else if ((sm_oid = git_submodule_wd_id(sm)) == NULL)
			rval = false;
		else
			rval = (git_oid__cmp(&baseitem->id, sm_oid) != 0);
165

166 167
		git_submodule_free(sm);
		return rval;
168 169
	}

170 171 172 173 174 175 176 177
	/* Look at the cache to decide if the workdir is modified.  If not,
	 * we can simply compare the oid in the cache to the baseitem instead
	 * of hashing the file.
	 */
	if ((ie = git_index_get_bypath(data->index, wditem->path, 0)) != NULL) {
		if (wditem->mtime.seconds == ie->mtime.seconds &&
			wditem->mtime.nanoseconds == ie->mtime.nanoseconds &&
			wditem->file_size == ie->file_size)
178
			return (git_oid__cmp(&baseitem->id, &ie->id) != 0);
179 180
	}

181 182 183 184
	/* 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)
185 186
		return true;

187
	if (git_diff__oid_for_entry(&oid, data->diff, wditem, NULL) < 0)
188 189
		return false;

190
	return (git_oid__cmp(&baseitem->id, &oid) != 0);
191 192 193 194 195 196
}

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

static int checkout_action_common(
197
	int *action,
198
	checkout_data *data,
199
	const git_diff_delta *delta,
200 201 202 203 204
	const git_index_entry *wd)
{
	git_checkout_notify_t notify = GIT_CHECKOUT_NOTIFY_NONE;

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

207
	if ((*action & CHECKOUT_ACTION__UPDATE_BLOB) != 0) {
208
		if (S_ISGITLINK(delta->new_file.mode))
209
			*action = (*action & ~CHECKOUT_ACTION__UPDATE_BLOB) |
210 211
				CHECKOUT_ACTION__UPDATE_SUBMODULE;

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

216 217 218
		notify = GIT_CHECKOUT_NOTIFY_UPDATED;
	}

219
	if ((*action & CHECKOUT_ACTION__CONFLICT) != 0)
220 221
		notify = GIT_CHECKOUT_NOTIFY_CONFLICT;

222
	return checkout_notify(data, notify, delta, wd);
223 224 225
}

static int checkout_action_no_wd(
226
	int *action,
227 228
	checkout_data *data,
	const git_diff_delta *delta)
229
{
230 231 232
	int error = 0;

	*action = CHECKOUT_ACTION__NONE;
233

234 235
	switch (delta->status) {
	case GIT_DELTA_UNMODIFIED: /* case 12 */
236 237 238 239
		error = checkout_notify(data, GIT_CHECKOUT_NOTIFY_DIRTY, delta, NULL);
		if (error)
			return error;
		*action = CHECKOUT_ACTION_IF(SAFE_CREATE, UPDATE_BLOB, NONE);
240 241
		break;
	case GIT_DELTA_ADDED:    /* case 2 or 28 (and 5 but not really) */
242
		*action = CHECKOUT_ACTION_IF(SAFE, UPDATE_BLOB, NONE);
243
		break;
244
	case GIT_DELTA_MODIFIED: /* case 13 (and 35 but not really) */
245
		*action = CHECKOUT_ACTION_IF(SAFE_CREATE, UPDATE_BLOB, CONFLICT);
246
		break;
247 248
	case GIT_DELTA_TYPECHANGE: /* case 21 (B->T) and 28 (T->B)*/
		if (delta->new_file.mode == GIT_FILEMODE_TREE)
249
			*action = CHECKOUT_ACTION_IF(SAFE, UPDATE_BLOB, NONE);
250 251
		break;
	case GIT_DELTA_DELETED: /* case 8 or 25 */
252
		*action = CHECKOUT_ACTION_IF(SAFE, REMOVE, NONE);
253
		break;
254 255
	default: /* impossible */
		break;
256 257
	}

258
	return checkout_action_common(action, data, delta, NULL);
259 260
}

261 262 263 264 265 266 267 268 269 270 271
static bool wd_item_is_removable(git_iterator *iter, const git_index_entry *wd)
{
	git_buf *full = NULL;

	if (wd->mode != GIT_FILEMODE_TREE)
		return true;
	if (git_iterator_current_workdir_path(&full, iter) < 0)
		return true;
	return !full || !git_path_contains(full, DOT_GIT);
}

272 273 274 275 276 277 278 279
static int checkout_queue_remove(checkout_data *data, const char *path)
{
	char *copy = git_pool_strdup(&data->pool, path);
	GITERR_CHECK_ALLOC(copy);
	return git_vector_insert(&data->removes, copy);
}

/* note that this advances the iterator over the wd item */
280 281 282
static int checkout_action_wd_only(
	checkout_data *data,
	git_iterator *workdir,
283
	const git_index_entry **wditem,
284 285
	git_vector *pathspec)
{
286
	int error = 0;
287
	bool remove = false;
288
	git_checkout_notify_t notify = GIT_CHECKOUT_NOTIFY_NONE;
289
	const git_index_entry *wd = *wditem;
290

291
	if (!git_pathspec__match(
292 293
			pathspec, wd->path,
			(data->strategy & GIT_CHECKOUT_DISABLE_PATHSPEC_MATCH) != 0,
294
			git_iterator_ignore_case(workdir), NULL, NULL))
295
		return git_iterator_advance(wditem, workdir);
296

297
	/* check if item is tracked in the index but not in the checkout diff */
298
	if (data->index != NULL) {
299 300
		size_t pos;

301
		error = git_index__find_pos(
302 303
			&pos, data->index, wd->path, 0, GIT_INDEX_STAGE_ANY);

304
		if (wd->mode != GIT_FILEMODE_TREE) {
305
			if (!error) { /* found by git_index__find_pos call */
306 307
				notify = GIT_CHECKOUT_NOTIFY_DIRTY;
				remove = ((data->strategy & GIT_CHECKOUT_FORCE) != 0);
308 309
			} else if (error != GIT_ENOTFOUND)
				return error;
310
			else
311
				error = 0; /* git_index__find_pos does not set error msg */
312 313 314 315 316 317 318 319 320 321 322
		} 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);

			if (e != NULL && data->diff->pfxcomp(e->path, wd->path) == 0) {
				notify = GIT_CHECKOUT_NOTIFY_DIRTY;
				remove = ((data->strategy & GIT_CHECKOUT_FORCE) != 0);
			}
		}
323
	}
324

325 326 327 328 329 330 331 332 333 334 335 336
	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;

		if (remove && wd_item_is_removable(workdir, wd))
			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 */
337 338
		bool over = false, removable = wd_item_is_removable(workdir, wd);
		git_iterator_status_t untracked_state;
339 340 341 342 343

		/* 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;
344

345 346
		error = git_iterator_advance_over_with_status(
			wditem, &untracked_state, workdir);
347 348 349 350
		if (error == GIT_ITEROVER)
			over = true;
		else if (error < 0)
			return error;
351

352
		if (untracked_state == GIT_ITERATOR_STATUS_IGNORED) {
353 354 355 356 357 358
			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);
		}
359

360 361 362 363 364 365 366 367
		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;
368 369
	}

370
	return error;
371 372
}

373 374 375 376 377 378
static bool submodule_is_config_only(
	checkout_data *data,
	const char *path)
{
	git_submodule *sm = NULL;
	unsigned int sm_loc = 0;
379
	bool rval = false;
380

381
	if (git_submodule_lookup(&sm, data->repo, path) < 0)
382 383
		return true;

384 385 386 387 388 389
	if (git_submodule_location(&sm_loc, sm) < 0 ||
		sm_loc == GIT_SUBMODULE_STATUS_IN_CONFIG)
		rval = true;

	git_submodule_free(sm);

390
	return rval;
391 392
}

393
static int checkout_action_with_wd(
394
	int *action,
395 396
	checkout_data *data,
	const git_diff_delta *delta,
397
	git_iterator *workdir,
398 399
	const git_index_entry *wd)
{
400
	*action = CHECKOUT_ACTION__NONE;
401 402 403

	switch (delta->status) {
	case GIT_DELTA_UNMODIFIED: /* case 14/15 or 33 */
404
		if (checkout_is_workdir_modified(data, &delta->old_file, wd)) {
405 406 407
			GITERR_CHECK_ERROR(
				checkout_notify(data, GIT_CHECKOUT_NOTIFY_DIRTY, delta, wd) );
			*action = CHECKOUT_ACTION_IF(FORCE, UPDATE_BLOB, NONE);
408
		}
409 410
		break;
	case GIT_DELTA_ADDED: /* case 3, 4 or 6 */
411 412 413 414
		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);
415 416 417
		break;
	case GIT_DELTA_DELETED: /* case 9 or 10 (or 26 but not really) */
		if (checkout_is_workdir_modified(data, &delta->old_file, wd))
418
			*action = CHECKOUT_ACTION_IF(FORCE, REMOVE, CONFLICT);
419
		else
420
			*action = CHECKOUT_ACTION_IF(SAFE, REMOVE, NONE);
421 422 423
		break;
	case GIT_DELTA_MODIFIED: /* case 16, 17, 18 (or 36 but not really) */
		if (checkout_is_workdir_modified(data, &delta->old_file, wd))
424
			*action = CHECKOUT_ACTION_IF(FORCE, UPDATE_BLOB, CONFLICT);
425
		else
426
			*action = CHECKOUT_ACTION_IF(SAFE, UPDATE_BLOB, NONE);
427 428
		break;
	case GIT_DELTA_TYPECHANGE: /* case 22, 23, 29, 30 */
429 430 431 432 433
		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...
				 */
434
				*action = CHECKOUT_ACTION_IF(SAFE, UPDATE_BLOB, NONE);
435 436 437 438 439
			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))
440
					*action = CHECKOUT_ACTION_IF(SAFE, UPDATE_BLOB, NONE);
441
				else
442
					*action = CHECKOUT_ACTION_IF(FORCE, REMOVE_AND_UPDATE, CONFLICT);
443
			} else
444
				*action = CHECKOUT_ACTION_IF(FORCE, REMOVE, CONFLICT);
445
		}
446
		else if (checkout_is_workdir_modified(data, &delta->old_file, wd))
447
			*action = CHECKOUT_ACTION_IF(FORCE, REMOVE_AND_UPDATE, CONFLICT);
448
		else
449
			*action = CHECKOUT_ACTION_IF(SAFE, REMOVE_AND_UPDATE, NONE);
450 451 452

		/* don't update if the typechange is to a tree */
		if (delta->new_file.mode == GIT_FILEMODE_TREE)
453
			*action = (*action & ~CHECKOUT_ACTION__UPDATE_BLOB);
454 455 456
		break;
	default: /* impossible */
		break;
457 458
	}

459
	return checkout_action_common(action, data, delta, wd);
460
}
461

462
static int checkout_action_with_wd_blocker(
463
	int *action,
464 465 466 467
	checkout_data *data,
	const git_diff_delta *delta,
	const git_index_entry *wd)
{
468
	*action = CHECKOUT_ACTION__NONE;
469

470 471 472
	switch (delta->status) {
	case GIT_DELTA_UNMODIFIED:
		/* should show delta as dirty / deleted */
473 474 475
		GITERR_CHECK_ERROR(
			checkout_notify(data, GIT_CHECKOUT_NOTIFY_DIRTY, delta, wd) );
		*action = CHECKOUT_ACTION_IF(FORCE, REMOVE_AND_UPDATE, NONE);
476 477 478
		break;
	case GIT_DELTA_ADDED:
	case GIT_DELTA_MODIFIED:
479
		*action = CHECKOUT_ACTION_IF(FORCE, REMOVE_AND_UPDATE, CONFLICT);
480 481
		break;
	case GIT_DELTA_DELETED:
482
		*action = CHECKOUT_ACTION_IF(FORCE, REMOVE, CONFLICT);
483 484 485
		break;
	case GIT_DELTA_TYPECHANGE:
		/* not 100% certain about this... */
486
		*action = CHECKOUT_ACTION_IF(FORCE, REMOVE_AND_UPDATE, CONFLICT);
487 488 489
		break;
	default: /* impossible */
		break;
490 491
	}

492
	return checkout_action_common(action, data, delta, wd);
493 494 495
}

static int checkout_action_with_wd_dir(
496
	int *action,
497 498
	checkout_data *data,
	const git_diff_delta *delta,
499
	git_iterator *workdir,
500 501
	const git_index_entry *wd)
{
502
	*action = CHECKOUT_ACTION__NONE;
503 504 505

	switch (delta->status) {
	case GIT_DELTA_UNMODIFIED: /* case 19 or 24 (or 34 but not really) */
506 507 508 509
		GITERR_CHECK_ERROR(
			checkout_notify(data, GIT_CHECKOUT_NOTIFY_DIRTY, delta, NULL));
		GITERR_CHECK_ERROR(
			checkout_notify(data, GIT_CHECKOUT_NOTIFY_UNTRACKED, NULL, wd));
510 511 512
		break;
	case GIT_DELTA_ADDED:/* case 4 (and 7 for dir) */
	case GIT_DELTA_MODIFIED: /* case 20 (or 37 but not really) */
513 514 515
		if (delta->old_file.mode == GIT_FILEMODE_COMMIT)
			/* expected submodule (and maybe found one) */;
		else if (delta->new_file.mode != GIT_FILEMODE_TREE)
516 517 518
			*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);
519 520
		break;
	case GIT_DELTA_DELETED: /* case 11 (and 27 for dir) */
521 522 523
		if (delta->old_file.mode != GIT_FILEMODE_TREE)
			GITERR_CHECK_ERROR(
				checkout_notify(data, GIT_CHECKOUT_NOTIFY_UNTRACKED, NULL, wd));
524 525 526
		break;
	case GIT_DELTA_TYPECHANGE: /* case 24 or 31 */
		if (delta->old_file.mode == GIT_FILEMODE_TREE) {
527 528 529 530 531 532
			/* 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.
			 */
533 534 535
			*action = CHECKOUT_ACTION_IF(SAFE, UPDATE_BLOB, NONE);
			if (*action != CHECKOUT_ACTION__NONE)
				*action |= CHECKOUT_ACTION__DEFER_REMOVE;
536
		}
537 538
		else if (delta->new_file.mode != GIT_FILEMODE_TREE)
			/* For typechange to dir, dir is already created so no action */
539
			*action = CHECKOUT_ACTION_IF(FORCE, REMOVE_AND_UPDATE, CONFLICT);
540 541 542
		break;
	default: /* impossible */
		break;
543 544
	}

545
	return checkout_action_common(action, data, delta, wd);
546 547
}

548
static int checkout_action(
549
	int *action,
550
	checkout_data *data,
551
	git_diff_delta *delta,
552
	git_iterator *workdir,
553
	const git_index_entry **wditem,
554 555
	git_vector *pathspec)
{
556
	int cmp = -1, error;
557 558
	int (*strcomp)(const char *, const char *) = data->diff->strcomp;
	int (*pfxcomp)(const char *str, const char *pfx) = data->diff->pfxcomp;
559
	int (*advance)(const git_index_entry **, git_iterator *) = NULL;
560 561 562 563

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

	while (1) {
564 565
		const git_index_entry *wd = *wditem;

566
		if (!wd)
567
			return checkout_action_no_wd(action, data, delta);
568

569 570 571 572 573 574 575 576 577 578 579 580 581
		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);

582
			if (cmp == 0) {
583 584
				if (wd->mode == GIT_FILEMODE_TREE) {
					/* case 2 - entry prefixed by workdir tree */
585 586 587
					error = git_iterator_advance_into_or_over(wditem, workdir);
					if (error < 0 && error != GIT_ITEROVER)
						goto done;
588 589 590 591 592
					continue;
				}

				/* case 3 maybe - wd contains non-dir where dir expected */
				if (delta->old_file.path[strlen(wd->path)] == '/') {
593 594 595 596
					error = checkout_action_with_wd_blocker(
						action, data, delta, wd);
					advance = git_iterator_advance;
					goto done;
597
				}
598
			}
599

600
			/* case 1 - handle wd item (if it matches pathspec) */
601 602
			error = checkout_action_wd_only(data, workdir, wditem, pathspec);
			if (error && error != GIT_ITEROVER)
603
				goto done;
604 605
			continue;
		}
606

607 608
		if (cmp == 0) {
			/* case 4 */
609
			error = checkout_action_with_wd(action, data, delta, workdir, wd);
610 611
			advance = git_iterator_advance;
			goto done;
612
		}
613

614
		cmp = pfxcomp(wd->path, delta->old_file.path);
615

616
		if (cmp == 0) { /* case 5 */
617
			if (wd->path[strlen(delta->old_file.path)] != '/')
618
				return checkout_action_no_wd(action, data, delta);
619 620 621

			if (delta->status == GIT_DELTA_TYPECHANGE) {
				if (delta->old_file.mode == GIT_FILEMODE_TREE) {
622
					error = checkout_action_with_wd(action, data, delta, workdir, wd);
623 624
					advance = git_iterator_advance_into;
					goto done;
625 626 627 628 629 630
				}

				if (delta->new_file.mode == GIT_FILEMODE_TREE ||
					delta->new_file.mode == GIT_FILEMODE_COMMIT ||
					delta->old_file.mode == GIT_FILEMODE_COMMIT)
				{
631
					error = checkout_action_with_wd(action, data, delta, workdir, wd);
632 633
					advance = git_iterator_advance;
					goto done;
634
				}
635 636
			}

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

640
		/* case 6 - wd is after delta */
641
		return checkout_action_no_wd(action, data, delta);
642 643
	}

644 645 646 647 648 649 650 651 652
done:
	if (!error && advance != NULL &&
		(error = advance(wditem, workdir)) < 0) {
		*wditem = NULL;
		if (error == GIT_ITEROVER)
			error = 0;
	}

	return error;
653 654
}

655 656 657 658 659 660 661 662
static int checkout_remaining_wd_items(
	checkout_data *data,
	git_iterator *workdir,
	const git_index_entry *wd,
	git_vector *spec)
{
	int error = 0;

663 664
	while (wd && !error)
		error = checkout_action_wd_only(data, workdir, &wd, spec);
665

666 667 668
	if (error == GIT_ITEROVER)
		error = 0;

669 670 671
	return error;
}

672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
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 &&
		(diff = checkout_idxentry_cmp(ca->ours, cb->theirs)) == 0)
		diff = checkout_idxentry_cmp(ca->theirs, cb->theirs);

	return diff;
}

699 700
int checkout_conflictdata_empty(
	const git_vector *conflicts, size_t idx, void *payload)
701 702 703
{
	checkout_conflictdata *conflict;

704 705
	GIT_UNUSED(payload);

706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
	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
743 744 745 746 747 748 749 750
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;
}

751 752 753 754 755
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
756 757 758
	if (conflict->submodule)
		return 0;

759
	if (conflict->ancestor) {
760
		if ((error = git_blob_lookup(&ancestor_blob, repo, &conflict->ancestor->id)) < 0)
761 762 763 764 765 766
			goto done;

		conflict->binary = git_blob_is_binary(ancestor_blob);
	}

	if (!conflict->binary && conflict->ours) {
767
		if ((error = git_blob_lookup(&our_blob, repo, &conflict->ours->id)) < 0)
768 769 770 771 772 773
			goto done;

		conflict->binary = git_blob_is_binary(our_blob);
	}

	if (!conflict->binary && conflict->theirs) {
774
		if ((error = git_blob_lookup(&their_blob, repo, &conflict->theirs->id)) < 0)
775 776 777 778 779 780 781 782 783 784 785 786 787
			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;
}

788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
static int checkout_conflicts_load(checkout_data *data, git_iterator *workdir, git_vector *pathspec)
{
	git_index_conflict_iterator *iterator = NULL;
	const git_index_entry *ancestor, *ours, *theirs;
	checkout_conflictdata *conflict;
	int error = 0;

	if ((error = git_index_conflict_iterator_new(&iterator, data->index)) < 0)
		goto done;

	data->conflicts._cmp = checkout_conflictdata_cmp;

	/* 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;

		conflict = git__calloc(1, sizeof(checkout_conflictdata));
		GITERR_CHECK_ALLOC(conflict);

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

Edward Thomson committed
812
		if ((error = checkout_conflict_detect_submodule(conflict)) < 0 ||
Ben Straub committed
813 814 815
		    (error = checkout_conflict_detect_binary(data->repo, conflict)) < 0)
		{
			git__free(conflict);
816
			goto done;
Ben Straub committed
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 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 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 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
		git_vector_insert(&data->conflicts, conflict);
	}

	if (error == GIT_ITEROVER)
		error = 0;

done:
	git_index_conflict_iterator_free(iterator);

	return error;
}

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;

	if (git_vector_bsearch2(&pos, &data->conflicts, checkout_conflicts_cmp_ancestor, path) < 0)
		return NULL;

	return git_vector_get(&data->conflicts, pos);
}

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

	git_vector_foreach(&data->conflicts, i, conflict) {
		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) {
		giterr_set(GITERR_INDEX, "A NAME entry exists without an ancestor");
		error = -1;
		goto done;
	}

	if (!name_entry->ours && !name_entry->theirs) {
		giterr_set(GITERR_INDEX, "A NAME entry exists without an ours or theirs");
		error = -1;
		goto done;
	}

	if ((ancestor = checkout_conflicts_search_ancestor(data,
		name_entry->ancestor)) == NULL) {
		giterr_set(GITERR_INDEX,
			"A NAME entry referenced ancestor entry '%s' which does not exist in the main index",
			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) {
			giterr_set(GITERR_INDEX,
				"A NAME entry referenced our entry '%s' which does not exist in the main index",
				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) {
			giterr_set(GITERR_INDEX,
				"A NAME entry referenced their entry '%s' which does not exist in the main index",
				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)
{
	const git_index_name_entry *name_entry;
	checkout_conflictdata *ancestor_conflict, *our_conflict, *their_conflict;
	size_t i, names;
	int error = 0;

	/* Juggle entries based on renames */
	names = git_index_name_entrycount(data->index);
Russell Belfer committed
967

968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
	for (i = 0; i < names; i++) {
		name_entry = git_index_name_get_byindex(data->index, i);

		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;
	}

1003 1004
	git_vector_remove_matching(
		&data->conflicts, checkout_conflictdata_empty, NULL);
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016

done:
	return error;
}

static int checkout_conflicts_mark_directoryfile(
	checkout_data *data)
{
	checkout_conflictdata *conflict;
	const git_index_entry *entry;
	size_t i, j, len;
	const char *path;
1017
	int prefixed, error = 0;
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

	len = git_index_entrycount(data->index);

	/* Find d/f conflicts */
	git_vector_foreach(&data->conflicts, i, conflict) {
		if ((conflict->ours && conflict->theirs) ||
			(!conflict->ours && !conflict->theirs))
			continue;

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

		if ((error = git_index_find(&j, data->index, path)) < 0) {
			if (error == GIT_ENOTFOUND)
				giterr_set(GITERR_INDEX,
					"Index inconsistency, could not find entry for expected conflict '%s'", path);

			goto done;
		}

		for (; j < len; j++) {
			if ((entry = git_index_get_byindex(data->index, j)) == NULL) {
				giterr_set(GITERR_INDEX,
					"Index inconsistency, truncated index while loading expected conflict '%s'", path);
				error = -1;
				goto done;
			}

1046
			prefixed = git_path_equal_or_prefixed(path, entry->path);
1047

1048
			if (prefixed == GIT_PATH_EQUAL)
1049 1050
				continue;

1051
			if (prefixed == GIT_PATH_PREFIX)
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
				conflict->directoryfile = 1;

			break;
		}
	}

done:
	return error;
}

static int checkout_get_conflicts(
	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 ||
		(error = checkout_conflicts_coalesce_renames(data)) < 0 ||
		(error = checkout_conflicts_mark_directoryfile(data)) < 0)
		goto done;

done:
	return error;
}

1081 1082 1083
static int checkout_get_actions(
	uint32_t **actions_ptr,
	size_t **counts_ptr,
1084 1085
	checkout_data *data,
	git_iterator *workdir)
1086
{
1087
	int error = 0, act;
1088 1089 1090 1091 1092 1093 1094
	const git_index_entry *wditem;
	git_vector pathspec = GIT_VECTOR_INIT, *deltas;
	git_pool pathpool = GIT_POOL_INIT_STRINGPOOL;
	git_diff_delta *delta;
	size_t i, *counts = NULL;
	uint32_t *actions = NULL;

1095
	if (data->opts.paths.count > 0 &&
1096
		git_pathspec__vinit(&pathspec, &data->opts.paths, &pathpool) < 0)
1097 1098
		return -1;

1099 1100
	if ((error = git_iterator_current(&wditem, workdir)) < 0 &&
		error != GIT_ITEROVER)
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
		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) {
1114
		error = checkout_action(&act, data, delta, workdir, &wditem, &pathspec);
1115
		if (error != 0)
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
			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]++;
	}
1129

1130
	error = checkout_remaining_wd_items(data, workdir, wditem, &pathspec);
1131
	if (error)
1132
		goto fail;
1133

1134 1135 1136 1137 1138
	counts[CHECKOUT_ACTION__REMOVE] += data->removes.length;

	if (counts[CHECKOUT_ACTION__CONFLICT] > 0 &&
		(data->strategy & GIT_CHECKOUT_ALLOW_CONFLICTS) == 0)
	{
1139 1140 1141 1142
		giterr_set(GITERR_CHECKOUT, "%d %s checkout",
			(int)counts[CHECKOUT_ACTION__CONFLICT],
			counts[CHECKOUT_ACTION__CONFLICT] == 1 ?
			"conflict prevents" : "conflicts prevent");
1143
		error = GIT_EMERGECONFLICT;
1144 1145 1146
		goto fail;
	}

1147

1148
	if ((error = checkout_get_conflicts(data, workdir, &pathspec)) < 0)
1149 1150 1151 1152
		goto fail;

	counts[CHECKOUT_ACTION__UPDATE_CONFLICT] = git_vector_length(&data->conflicts);

1153
	git_pathspec__vfree(&pathspec);
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
	git_pool_clear(&pathpool);

	return 0;

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

1164
	git_pathspec__vfree(&pathspec);
1165 1166 1167 1168 1169
	git_pool_clear(&pathpool);

	return error;
}

1170
static int buffer_to_file(
1171
	struct stat *st,
1172
	git_buf *buf,
1173
	const char *path,
1174
	mode_t dir_mode,
1175 1176 1177
	int file_open_flags,
	mode_t file_mode)
{
1178
	int error;
1179

1180 1181
	if ((error = git_futils_mkpath2file(path, dir_mode)) < 0)
		return error;
1182

1183
	if ((error = git_futils_writebuffer(
1184
			buf, path, file_open_flags, file_mode)) < 0)
1185
		return error;
1186

1187 1188
	if (st != NULL && (error = p_stat(path, st)) < 0)
		giterr_set(GITERR_OS, "Error statting '%s'", path);
1189

1190
	else if (GIT_PERMS_IS_EXEC(file_mode) &&
1191
			(error = p_chmod(path, file_mode)) < 0)
1192 1193
		giterr_set(GITERR_OS, "Failed to set permissions on '%s'", path);

1194
	return error;
Ben Straub committed
1195 1196
}

1197
static int blob_content_to_file(
1198
	struct stat *st,
1199 1200
	git_blob *blob,
	const char *path,
1201
	const char * hint_path,
1202
	mode_t entry_filemode,
1203
	git_checkout_options *opts)
1204
{
1205 1206
	int error = 0;
	mode_t file_mode = opts->file_mode ? opts->file_mode : entry_filemode;
1207
	git_buf out = GIT_BUF_INIT;
1208
	git_filter_list *fl = NULL;
1209

1210 1211 1212
	if (hint_path == NULL)
		hint_path = path;

1213
	if (!opts->disable_filters)
1214
		error = git_filter_list_load(
1215 1216
			&fl, git_blob_owner(blob), blob, hint_path,
			GIT_FILTER_TO_WORKTREE, GIT_FILTER_OPT_DEFAULT);
1217

1218 1219
	if (!error)
		error = git_filter_list_apply_to_blob(&out, fl, blob);
1220

1221
	git_filter_list_free(fl);
1222

1223 1224 1225
	if (!error) {
		error = buffer_to_file(
			st, &out, path, opts->dir_mode, opts->file_open_flags, file_mode);
1226

1227
		st->st_mode = entry_filemode;
1228

1229
		git_buf_free(&out);
1230
	}
1231 1232

	return error;
1233 1234
}

1235
static int blob_content_to_link(
1236 1237 1238 1239 1240
	struct stat *st,
	git_blob *blob,
	const char *path,
	mode_t dir_mode,
	int can_symlink)
1241 1242 1243
{
	git_buf linktarget = GIT_BUF_INIT;
	int error;
1244

1245
	if ((error = git_futils_mkpath2file(path, dir_mode)) < 0)
Linquize committed
1246
		return error;
1247

1248 1249
	if ((error = git_blob__getbuf(&linktarget, blob)) < 0)
		return error;
1250

1251 1252
	if (can_symlink) {
		if ((error = p_symlink(git_buf_cstr(&linktarget), path)) < 0)
1253
			giterr_set(GITERR_OS, "Could not create symlink %s\n", path);
1254
	} else {
1255
		error = git_futils_fake_symlink(git_buf_cstr(&linktarget), path);
1256 1257 1258 1259 1260 1261 1262 1263
	}

	if (!error) {
		if ((error = p_lstat(path, st)) < 0)
			giterr_set(GITERR_CHECKOUT, "Could not stat symlink %s", path);

		st->st_mode = GIT_FILEMODE_LINK;
	}
1264

1265 1266 1267
	git_buf_free(&linktarget);

	return error;
1268 1269
}

1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
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 */
1282
	git_index_entry__init_from_stat(&entry, st, true);
1283
	git_oid_cpy(&entry.id, &file->id);
1284 1285 1286 1287

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

1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
static int checkout_submodule_update_index(
	checkout_data *data,
	const git_diff_file *file)
{
	struct stat st;

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

	git_buf_truncate(&data->path, data->workdir_len);
	if (git_buf_puts(&data->path, file->path) < 0)
		return -1;

	if (p_stat(git_buf_cstr(&data->path), &st) < 0) {
		giterr_set(
			GITERR_CHECKOUT, "Could not stat submodule %s\n", file->path);
		return GIT_ENOTFOUND;
	}

	st.st_mode = GIT_FILEMODE_COMMIT;

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

1313
static int checkout_submodule(
1314
	checkout_data *data,
1315 1316
	const git_diff_file *file)
{
1317 1318
	int error = 0;

1319
	/* Until submodules are supported, UPDATE_ONLY means do nothing here */
1320
	if ((data->strategy & GIT_CHECKOUT_UPDATE_ONLY) != 0)
1321 1322
		return 0;

1323
	if ((error = git_futils_mkdir(
1324
			file->path, data->opts.target_directory,
1325 1326
			data->opts.dir_mode, GIT_MKDIR_PATH)) < 0)
		return error;
1327

1328
	if ((error = git_submodule_lookup(NULL, data->repo, file->path)) < 0) {
1329 1330 1331 1332 1333 1334 1335 1336
		/* 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) {
			giterr_clear();
			return checkout_submodule_update_index(data, file);
		}

1337
		return error;
1338
	}
1339

1340
	/* TODO: Support checkout_strategy options.  Two circumstances:
1341 1342 1343 1344
	 * 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
	 *
1345 1346
	 * Checkout will not execute a pull on the submodule, but a clone
	 * command should probably be able to.  Do we need a submodule callback?
1347 1348
	 */

1349
	return checkout_submodule_update_index(data, file);
1350 1351
}

1352
static void report_progress(
1353
	checkout_data *data,
1354
	const char *path)
1355
{
1356 1357
	if (data->opts.progress_cb)
		data->opts.progress_cb(
1358
			path, data->completed_steps, data->total_steps,
1359
			data->opts.progress_payload);
1360 1361
}

1362
static int checkout_safe_for_update_only(const char *path, mode_t expected_mode)
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
{
	struct stat st;

	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 */
		giterr_set(GITERR_OS, "Failed to stat file '%s'", path);
		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;
}

1383
static int checkout_write_content(
1384
	checkout_data *data,
1385 1386 1387 1388 1389
	const git_oid *oid,
	const char *full_path,
	const char *hint_path,
	unsigned int mode,
	struct stat *st)
1390
{
1391
	int error = 0;
1392
	git_blob *blob;
1393

1394
	if ((error = git_blob_lookup(&blob, data->repo, oid)) < 0)
1395 1396
		return error;

1397
	if (S_ISLNK(mode))
1398
		error = blob_content_to_link(
1399
			st, blob, full_path, data->opts.dir_mode, data->can_symlink);
1400
	else
1401
		error = blob_content_to_file(
1402
			st, blob, full_path, hint_path, mode, &data->opts);
1403 1404 1405

	git_blob_free(blob);

1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416
	/* 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))
	{
		giterr_clear();
		error = 0;
	}

1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
	return error;
}

static int checkout_blob(
	checkout_data *data,
	const git_diff_file *file)
{
	int error = 0;
	struct stat st;

	git_buf_truncate(&data->path, data->workdir_len);
	if (git_buf_puts(&data->path, file->path) < 0)
		return -1;

	if ((data->strategy & GIT_CHECKOUT_UPDATE_ONLY) != 0) {
1432
		int rval = checkout_safe_for_update_only(
1433 1434 1435 1436 1437
			git_buf_cstr(&data->path), file->mode);
		if (rval <= 0)
			return rval;
	}

1438
	error = checkout_write_content(
1439
		data, &file->id, git_buf_cstr(&data->path), NULL, file->mode, &st);
1440

1441 1442 1443 1444
	/* update the index unless prevented */
	if (!error && (data->strategy & GIT_CHECKOUT_DONT_UPDATE_INDEX) == 0)
		error = checkout_update_index(data, file, &st);

1445 1446 1447 1448
	/* update the submodule data if this was a new .gitmodules file */
	if (!error && strcmp(file->path, ".gitmodules") == 0)
		data->reload_submodules = true;

1449 1450 1451
	return error;
}

1452 1453
static int checkout_remove_the_old(
	unsigned int *actions,
1454
	checkout_data *data)
1455
{
1456
	int error = 0;
1457
	git_diff_delta *delta;
1458
	const char *str;
1459
	size_t i;
1460 1461 1462
	const char *workdir = git_buf_cstr(&data->path);
	uint32_t flg = GIT_RMDIR_EMPTY_PARENTS |
		GIT_RMDIR_REMOVE_FILES | GIT_RMDIR_REMOVE_BLOCKERS;
1463

1464 1465 1466
	if (data->opts.checkout_strategy & GIT_CHECKOUT_SKIP_LOCKED_DIRECTORIES)
		flg |= GIT_RMDIR_SKIP_NONEMPTY;

1467
	git_buf_truncate(&data->path, data->workdir_len);
1468

1469
	git_vector_foreach(&data->diff->deltas, i, delta) {
1470
		if (actions[i] & CHECKOUT_ACTION__REMOVE) {
1471
			error = git_futils_rmdir_r(delta->old_file.path, workdir, flg);
1472
			if (error < 0)
1473 1474 1475
				return error;

			data->completed_steps++;
1476
			report_progress(data, delta->old_file.path);
1477 1478 1479 1480 1481 1482 1483

			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);
			}
1484 1485 1486
		}
	}

1487 1488 1489 1490 1491 1492
	git_vector_foreach(&data->removes, i, str) {
		error = git_futils_rmdir_r(str, workdir, flg);
		if (error < 0)
			return error;

		data->completed_steps++;
1493
		report_progress(data, str);
1494 1495 1496 1497

		if ((data->strategy & GIT_CHECKOUT_DONT_UPDATE_INDEX) == 0 &&
			data->index != NULL)
		{
1498 1499 1500 1501
			if (str[strlen(str) - 1] == '/')
				(void)git_index_remove_directory(data->index, str, 0);
			else
				(void)git_index_remove(data->index, str, 0);
1502
		}
1503 1504 1505 1506 1507 1508 1509 1510 1511
	}

	return 0;
}

static int checkout_deferred_remove(git_repository *repo, const char *path)
{
#if 0
	int error = git_futils_rmdir_r(
1512
		path, data->opts.target_directory, GIT_RMDIR_EMPTY_PARENTS);
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522

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

	return error;
#else
	GIT_UNUSED(repo);
	GIT_UNUSED(path);
1523
	assert(false);
1524
	return 0;
1525
#endif
1526 1527 1528 1529
}

static int checkout_create_the_new(
	unsigned int *actions,
1530
	checkout_data *data)
1531
{
1532
	int error = 0;
1533 1534 1535
	git_diff_delta *delta;
	size_t i;

1536
	git_vector_foreach(&data->diff->deltas, i, delta) {
1537 1538 1539 1540 1541 1542 1543 1544 1545
		if (actions[i] & CHECKOUT_ACTION__DEFER_REMOVE) {
			/* this had a blocker directory that should only be removed iff
			 * all of the contents of the directory were safely removed
			 */
			if ((error = checkout_deferred_remove(
					data->repo, delta->old_file.path)) < 0)
				return error;
		}

1546
		if (actions[i] & CHECKOUT_ACTION__UPDATE_BLOB) {
1547
			error = checkout_blob(data, &delta->new_file);
1548
			if (error < 0)
1549 1550 1551
				return error;

			data->completed_steps++;
1552
			report_progress(data, delta->new_file.path);
1553 1554 1555 1556 1557 1558 1559 1560
		}
	}

	return 0;
}

static int checkout_create_submodules(
	unsigned int *actions,
1561
	checkout_data *data)
1562
{
1563
	int error = 0;
1564 1565 1566
	git_diff_delta *delta;
	size_t i;

1567 1568
	/* initial reload of submodules if .gitmodules was changed */
	if (data->reload_submodules &&
1569
		(error = git_submodule_reload_all(data->repo, 1)) < 0)
1570 1571
		return error;

1572
	git_vector_foreach(&data->diff->deltas, i, delta) {
1573 1574 1575 1576 1577 1578 1579 1580 1581
		if (actions[i] & CHECKOUT_ACTION__DEFER_REMOVE) {
			/* this has a blocker directory that should only be removed iff
			 * all of the contents of the directory were safely removed
			 */
			if ((error = checkout_deferred_remove(
					data->repo, delta->old_file.path)) < 0)
				return error;
		}

1582
		if (actions[i] & CHECKOUT_ACTION__UPDATE_SUBMODULE) {
1583
			int error = checkout_submodule(data, &delta->new_file);
1584 1585 1586 1587
			if (error < 0)
				return error;

			data->completed_steps++;
1588
			report_progress(data, delta->new_file.path);
1589 1590 1591
		}
	}

1592
	/* final reload once submodules have been updated */
1593
	return git_submodule_reload_all(data->repo, 1);
1594 1595
}

1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610
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)) &&
		!(error = git_reference_peel(&head, ref, GIT_OBJ_TREE)))
		*out = (git_tree *)head;

	git_reference_free(ref);

	return error;
}

1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687

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);

		giterr_set(GITERR_CHECKOUT, "Could not write '%s': working directory file exists", path);
		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;
	struct stat st;
	int error;

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

	git_buf_truncate(&data->path, data->workdir_len);
	if (git_buf_puts(&data->path, side->path) < 0)
		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";

		if (checkout_path_suffixed(&data->path, suffix) < 0)
			return -1;

		hint_path = side->path;
	}

	if ((data->strategy & GIT_CHECKOUT_UPDATE_ONLY) != 0 &&
1688
		(error = checkout_safe_for_update_only(git_buf_cstr(&data->path), side->mode)) <= 0)
1689 1690
		return error;

1691
	return checkout_write_content(data,
1692
		&side->id, git_buf_cstr(&data->path), hint_path, side->mode, &st);
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738
}

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,
1739 1740
		path_suffixed = GIT_BUF_INIT, path_workdir = GIT_BUF_INIT,
		in_data = GIT_BUF_INIT, out_data = GIT_BUF_INIT;
1741 1742
	git_merge_file_options opts = GIT_MERGE_FILE_OPTIONS_INIT;
	git_merge_file_result result = {0};
1743
	git_filebuf output = GIT_FILEBUF_INIT;
1744
	git_filter_list *fl = NULL;
1745 1746
	int error = 0;

1747
	if (data->opts.checkout_strategy & GIT_CHECKOUT_CONFLICT_STYLE_DIFF3)
1748
		opts.flags |= GIT_MERGE_FILE_STYLE_DIFF3;
1749

1750 1751 1752 1753 1754 1755
	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";
1756 1757 1758 1759 1760 1761 1762 1763

	/* 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(
1764
			&our_label, opts.our_label, conflict->ours->path)) < 0 ||
1765
			(error = conflict_entry_name(
1766
			&their_label, opts.their_label, conflict->theirs->path)) < 0)
1767 1768
			goto done;

1769 1770
		opts.our_label = git_buf_cstr(&our_label);
		opts.their_label = git_buf_cstr(&their_label);
1771 1772
	}

1773 1774
	if ((error = git_merge_file_from_index(&result, data->repo,
		conflict->ancestor, conflict->ours, conflict->theirs, &opts)) < 0)
1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786
		goto done;

	if (result.path == NULL || result.mode == 0) {
		giterr_set(GITERR_CHECKOUT, "Could not merge contents of file");
		error = GIT_EMERGECONFLICT;
		goto done;
	}

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

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

1790
	if (!data->opts.disable_filters) {
1791 1792 1793 1794
		in_data.ptr = (char *)result.ptr;
		in_data.size = result.len;

		if ((error = git_filter_list_load(&fl, data->repo, NULL, git_buf_cstr(&path_workdir),
1795 1796 1797
				GIT_FILTER_TO_WORKTREE, GIT_FILTER_OPT_DEFAULT)) < 0 ||
			(error = git_filter_list_apply_to_data(&out_data, fl, &in_data)) < 0)
			goto done;
1798 1799 1800 1801
	} else {
		out_data.ptr = (char *)result.ptr;
		out_data.size = result.len;
	}
1802

1803
	if ((error = git_futils_mkpath2file(path_workdir.ptr, 0755)) < 0 ||
1804 1805
		(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 ||
1806
		(error = git_filebuf_commit(&output)) < 0)
1807 1808 1809
		goto done;

done:
1810 1811 1812
	git_filter_list_free(fl);

	git_buf_free(&out_data);
1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829
	git_buf_free(&our_label);
	git_buf_free(&their_label);

	git_merge_file_result_free(&result);
	git_buf_free(&path_workdir);
	git_buf_free(&path_suffixed);

	return error;
}

static int checkout_create_conflicts(checkout_data *data)
{
	checkout_conflictdata *conflict;
	size_t i;
	int error = 0;

	git_vector_foreach(&data->conflicts, i, conflict) {
1830

1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873
		/* 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
1874 1875 1876 1877
		/* If any side is a gitlink, do nothing. */
		else if (conflict->submodule)
			error = 0;

1878 1879 1880 1881 1882
		/* If any side is binary, write the ours side */
		else if (conflict->binary)
			error = checkout_write_entry(data, conflict, conflict->ours);

		else if (!error)
1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897
			error = checkout_write_merge(data, conflict);

		if (error)
			break;

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

	return error;
}


1898 1899 1900 1901 1902 1903 1904 1905 1906 1907
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);

1908
	git_vector_free_deep(&data->conflicts);
1909

1910 1911 1912 1913
	git__free(data->pfx);
	data->pfx = NULL;

	git_buf_free(&data->path);
1914
	git_buf_free(&data->tmp);
1915 1916 1917

	git_index_free(data->index);
	data->index = NULL;
1918 1919 1920 1921
}

static int checkout_data_init(
	checkout_data *data,
1922
	git_iterator *target,
1923
	const git_checkout_options *proposed)
1924
{
1925
	int error = 0;
1926
	git_repository *repo = git_iterator_owner(target);
1927

1928 1929 1930 1931
	memset(data, 0, sizeof(*data));

	if (!repo) {
		giterr_set(GITERR_CHECKOUT, "Cannot checkout nothing");
1932
		return -1;
1933
	}
1934

1935 1936
	if ((!proposed || !proposed->target_directory) &&
		(error = git_repository__ensure_not_bare(repo, "checkout")) < 0)
1937
		return error;
1938

1939 1940 1941
	data->repo = repo;

	GITERR_CHECK_VERSION(
1942
		proposed, GIT_CHECKOUT_OPTIONS_VERSION, "git_checkout_options");
1943 1944

	if (!proposed)
1945
		GIT_INIT_STRUCTURE(&data->opts, GIT_CHECKOUT_OPTIONS_VERSION);
1946
	else
1947
		memmove(&data->opts, proposed, sizeof(git_checkout_options));
1948

1949 1950 1951 1952 1953 1954 1955
	if (!data->opts.target_directory)
		data->opts.target_directory = git_repository_workdir(repo);
	else if (!git_path_isdir(data->opts.target_directory) &&
			 (error = git_futils_mkdir(data->opts.target_directory, NULL,
					GIT_DIR_MODE, GIT_MKDIR_VERIFY_DIR)) < 0)
		goto cleanup;

1956 1957
	/* refresh config and index content unless NO_REFRESH is given */
	if ((data->opts.checkout_strategy & GIT_CHECKOUT_NO_REFRESH) == 0) {
1958 1959 1960 1961
		git_config *cfg;

		if ((error = git_repository_config__weakptr(&cfg, repo)) < 0 ||
			(error = git_config_refresh(cfg)) < 0)
1962 1963
			goto cleanup;

1964 1965 1966 1967
		/* if we are checking out the index, don't reload,
		 * otherwise get index and force reload
		 */
		if ((data->index = git_iterator_get_index(target)) != NULL) {
1968 1969 1970 1971
			GIT_REFCOUNT_INC(data->index);
		} else {
			/* otherwise, grab and reload the index */
			if ((error = git_repository_index(&data->index, data->repo)) < 0 ||
1972
				(error = git_index_read(data->index, true)) < 0)
1973
				goto cleanup;
1974

1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985
			/* cannot checkout if unresolved conflicts exist */
			if ((data->opts.checkout_strategy & GIT_CHECKOUT_FORCE) == 0 &&
				git_index_has_conflicts(data->index)) {
				error = GIT_EMERGECONFLICT;
				giterr_set(GITERR_CHECKOUT,
					"unresolved conflicts exist in the index");
				goto cleanup;
			}

			/* clean conflict data when doing a tree or commit checkout */
			git_index_name_clear(data->index);
Edward Thomson committed
1986
			git_index_reuc_clear(data->index);
1987 1988
		}
	}
1989

1990
	/* if you are forcing, definitely allow safe updates */
1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007
	if ((data->opts.checkout_strategy & GIT_CHECKOUT_FORCE) != 0)
		data->opts.checkout_strategy |= GIT_CHECKOUT_SAFE_CREATE;
	if ((data->opts.checkout_strategy & GIT_CHECKOUT_SAFE_CREATE) != 0)
		data->opts.checkout_strategy |= GIT_CHECKOUT_SAFE;

	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);

2008 2009 2010
	if ((error = git_repository__cvar(
			 &data->can_symlink, repo, GIT_CVAR_SYMLINKS)) < 0)
		goto cleanup;
2011

2012 2013
	if (!data->opts.baseline) {
		data->opts_free_baseline = true;
2014

2015 2016
		error = checkout_lookup_head_tree(&data->opts.baseline, repo);

2017
		if (error == GIT_EUNBORNBRANCH) {
2018 2019 2020 2021 2022
			error = 0;
			giterr_clear();
		}

		if (error < 0)
2023 2024 2025
			goto cleanup;
	}

2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048
	if ((data->opts.checkout_strategy &
		(GIT_CHECKOUT_CONFLICT_STYLE_MERGE | GIT_CHECKOUT_CONFLICT_STYLE_DIFF3)) == 0) {
		const char *conflict_style;
		git_config *cfg = NULL;

		if ((error = git_repository_config__weakptr(&cfg, repo)) < 0 ||
			(error = git_config_get_string(&conflict_style, cfg, "merge.conflictstyle")) < 0 ||
			error == GIT_ENOTFOUND)
			;
		else if (error)
			goto cleanup;
		else if (strcmp(conflict_style, "merge") == 0)
			data->opts.checkout_strategy |= GIT_CHECKOUT_CONFLICT_STYLE_MERGE;
		else if (strcmp(conflict_style, "diff3") == 0)
			data->opts.checkout_strategy |= GIT_CHECKOUT_CONFLICT_STYLE_DIFF3;
		else {
			giterr_set(GITERR_CHECKOUT, "unknown style '%s' given for 'merge.conflictstyle'",
				conflict_style);
			error = -1;
			goto cleanup;
		}
	}

2049
	if ((error = git_vector_init(&data->removes, 0, git__strcmp_cb)) < 0 ||
2050
		(error = git_vector_init(&data->conflicts, 0, NULL)) < 0 ||
2051
		(error = git_pool_init(&data->pool, 1, 0)) < 0 ||
2052 2053
		(error = git_buf_puts(&data->path, data->opts.target_directory)) < 0 ||
		(error = git_path_to_dir(&data->path)) < 0)
2054 2055 2056 2057 2058 2059 2060
		goto cleanup;

	data->workdir_len = git_buf_len(&data->path);

cleanup:
	if (error < 0)
		checkout_data_clear(data);
2061 2062 2063 2064

	return error;
}

2065 2066
int git_checkout_iterator(
	git_iterator *target,
2067
	const git_checkout_options *opts)
2068 2069
{
	int error = 0;
2070 2071
	git_iterator *baseline = NULL, *workdir = NULL;
	checkout_data data = {0};
2072
	git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT;
2073 2074
	uint32_t *actions = NULL;
	size_t *counts = NULL;
2075
	git_iterator_flag_t iterflags = 0;
2076

2077
	/* initialize structures and options */
2078
	error = checkout_data_init(&data, target, opts);
2079 2080
	if (error < 0)
		return error;
Ben Straub committed
2081

2082 2083 2084 2085 2086 2087 2088 2089
	diff_opts.flags =
		GIT_DIFF_INCLUDE_UNMODIFIED |
		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 |
		GIT_DIFF_SKIP_BINARY_CHECK;
2090 2091
	if (data.opts.checkout_strategy & GIT_CHECKOUT_DISABLE_PATHSPEC_MATCH)
		diff_opts.flags |= GIT_DIFF_DISABLE_PATHSPEC_MATCH;
2092 2093 2094 2095
	if (data.opts.paths.count > 0)
		diff_opts.pathspec = data.opts.paths;

	/* set up iterators */
2096 2097 2098 2099

	iterflags = git_iterator_ignore_case(target) ?
		GIT_ITERATOR_IGNORE_CASE : GIT_ITERATOR_DONT_IGNORE_CASE;

2100
	if ((error = git_iterator_reset(target, data.pfx, data.pfx)) < 0 ||
2101 2102 2103
		(error = git_iterator_for_workdir_ext(
			&workdir, data.repo, data.opts.target_directory,
			iterflags | GIT_ITERATOR_DONT_AUTOEXPAND,
2104
			data.pfx, data.pfx)) < 0 ||
2105
		(error = git_iterator_for_tree(
2106 2107
			&baseline, data.opts.baseline,
			iterflags, data.pfx, data.pfx)) < 0)
2108 2109
		goto cleanup;

2110 2111
	/* Should not have case insensitivity mismatch */
	assert(git_iterator_ignore_case(workdir) == git_iterator_ignore_case(baseline));
2112

2113 2114
	/* Generate baseline-to-target diff which will include an entry for
	 * every possible update that might need to be made.
2115 2116
	 */
	if ((error = git_diff__from_iterators(
2117
			&data.diff, data.repo, baseline, target, &diff_opts)) < 0)
2118 2119
		goto cleanup;

2120
	/* Loop through diff (and working directory iterator) building a list of
2121 2122
	 * actions to be taken, plus look for conflicts and send notifications,
	 * then loop through conflicts.
2123
	 */
2124
	if ((error = checkout_get_actions(&actions, &counts, &data, workdir)) != 0)
2125 2126
		goto cleanup;

2127
	data.total_steps = counts[CHECKOUT_ACTION__REMOVE] +
2128
		counts[CHECKOUT_ACTION__UPDATE_BLOB] +
2129 2130
		counts[CHECKOUT_ACTION__UPDATE_SUBMODULE] +
		counts[CHECKOUT_ACTION__UPDATE_CONFLICT];
2131

2132
	report_progress(&data, NULL); /* establish 0 baseline */
2133

2134 2135 2136
	/* To deal with some order dependencies, perform remaining checkout
	 * in three passes: removes, then update blobs, then update submodules.
	 */
2137
	if (counts[CHECKOUT_ACTION__REMOVE] > 0 &&
2138
		(error = checkout_remove_the_old(actions, &data)) < 0)
2139 2140
		goto cleanup;

2141
	if (counts[CHECKOUT_ACTION__UPDATE_BLOB] > 0 &&
2142
		(error = checkout_create_the_new(actions, &data)) < 0)
2143 2144
		goto cleanup;

2145
	if (counts[CHECKOUT_ACTION__UPDATE_SUBMODULE] > 0 &&
2146
		(error = checkout_create_submodules(actions, &data)) < 0)
2147 2148
		goto cleanup;

2149
	if (counts[CHECKOUT_ACTION__UPDATE_CONFLICT] > 0 &&
2150
		(error = checkout_create_conflicts(&data)) < 0)
2151
		goto cleanup;
2152

2153
	assert(data.completed_steps == data.total_steps);
2154

2155
cleanup:
2156 2157 2158 2159
	if (!error && data.index != NULL &&
		(data.strategy & GIT_CHECKOUT_DONT_UPDATE_INDEX) == 0)
		error = git_index_write(data.index);

2160
	git_diff_free(data.diff);
2161
	git_iterator_free(workdir);
2162
	git_iterator_free(baseline);
2163 2164
	git__free(actions);
	git__free(counts);
2165
	checkout_data_clear(&data);
2166 2167 2168 2169 2170 2171 2172

	return error;
}

int git_checkout_index(
	git_repository *repo,
	git_index *index,
2173
	const git_checkout_options *opts)
2174 2175
{
	int error;
2176
	git_iterator *index_i;
2177

2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190
	if (!index && !repo) {
		giterr_set(GITERR_CHECKOUT,
			"Must provide either repository or index to checkout");
		return -1;
	}
	if (index && repo && git_index_owner(index) != repo) {
		giterr_set(GITERR_CHECKOUT,
			"Index to checkout does not match repository");
		return -1;
	}

	if (!repo)
		repo = git_index_owner(index);
2191 2192 2193

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

2196
	if (!(error = git_iterator_for_index(&index_i, index, 0, NULL, NULL)))
2197
		error = git_checkout_iterator(index_i, opts);
2198 2199

	git_iterator_free(index_i);
2200
	git_index_free(index);
2201

2202 2203 2204 2205 2206
	return error;
}

int git_checkout_tree(
	git_repository *repo,
Vicent Marti committed
2207
	const git_object *treeish,
2208
	const git_checkout_options *opts)
2209
{
2210
	int error;
2211 2212
	git_tree *tree = NULL;
	git_iterator *tree_i = NULL;
2213

2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226
	if (!treeish && !repo) {
		giterr_set(GITERR_CHECKOUT,
			"Must provide either repository or tree to checkout");
		return -1;
	}
	if (treeish && repo && git_object_owner(treeish) != repo) {
		giterr_set(GITERR_CHECKOUT,
			"Object to checkout does not match repository");
		return -1;
	}

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

2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242
	if (treeish) {
		if (git_object_peel((git_object **)&tree, treeish, GIT_OBJ_TREE) < 0) {
			giterr_set(
				GITERR_CHECKOUT, "Provided object cannot be peeled to a tree");
			return -1;
		}
	}
	else {
		if ((error = checkout_lookup_head_tree(&tree, repo)) < 0) {
			if (error != GIT_EUNBORNBRANCH)
				giterr_set(
					GITERR_CHECKOUT,
					"HEAD could not be peeled to a tree and no treeish given");
			return error;
		}
2243 2244
	}

2245
	if (!(error = git_iterator_for_tree(&tree_i, tree, 0, NULL, NULL)))
2246
		error = git_checkout_iterator(tree_i, opts);
2247

2248
	git_iterator_free(tree_i);
2249
	git_tree_free(tree);
2250

2251
	return error;
2252 2253
}

2254 2255
int git_checkout_head(
	git_repository *repo,
2256
	const git_checkout_options *opts)
2257
{
2258
	assert(repo);
2259
	return git_checkout_tree(repo, NULL, opts);
2260
}
2261

2262
int git_checkout_init_options(git_checkout_options *opts, unsigned int version)
2263
{
2264 2265 2266
	GIT_INIT_STRUCTURE_FROM_TEMPLATE(
		opts, version, git_checkout_options, GIT_CHECKOUT_OPTIONS_INIT);
	return 0;
2267
}