stash.c 27.1 KB
Newer Older
nulltoken committed
1
/*
Edward Thomson committed
2
 * Copyright (C) the libgit2 contributors. All rights reserved.
nulltoken committed
3 4 5 6 7 8
 *
 * 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 "common.h"
9

nulltoken committed
10 11
#include "repository.h"
#include "commit.h"
12
#include "message.h"
nulltoken committed
13 14
#include "tree.h"
#include "reflog.h"
15
#include "blob.h"
nulltoken committed
16 17 18 19
#include "git2/diff.h"
#include "git2/stash.h"
#include "git2/status.h"
#include "git2/checkout.h"
20
#include "git2/index.h"
21
#include "git2/transaction.h"
22
#include "git2/merge.h"
23
#include "index.h"
Ben Straub committed
24
#include "signature.h"
25 26
#include "iterator.h"
#include "merge.h"
27
#include "diff.h"
28
#include "diff_generate.h"
nulltoken committed
29 30 31

static int create_error(int error, const char *msg)
{
32
	git_error_set(GIT_ERROR_STASH, "cannot stash changes - %s", msg);
nulltoken committed
33 34 35 36 37 38 39
	return error;
}

static int retrieve_head(git_reference **out, git_repository *repo)
{
	int error = git_repository_head(out, repo);

40
	if (error == GIT_EUNBORNBRANCH)
41
		return create_error(error, "you do not have the initial commit yet.");
nulltoken committed
42 43 44 45 46 47 48 49 50

	return error;
}

static int append_abbreviated_oid(git_buf *out, const git_oid *b_commit)
{
	char *formatted_oid;

	formatted_oid = git_oid_allocfmt(b_commit);
51
	GIT_ERROR_CHECK_ALLOC(formatted_oid);
nulltoken committed
52 53 54 55 56 57 58 59 60

	git_buf_put(out, formatted_oid, 7);
	git__free(formatted_oid);

	return git_buf_oom(out) ? -1 : 0;
}

static int append_commit_description(git_buf *out, git_commit* commit)
{
61
	const char *summary = git_commit_summary(commit);
62
	GIT_ERROR_CHECK_ALLOC(summary);
nulltoken committed
63 64 65 66 67

	if (append_abbreviated_oid(out, git_commit_id(commit)) < 0)
		return -1;

	git_buf_putc(out, ' ');
68
	git_buf_puts(out, summary);
nulltoken committed
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
	git_buf_putc(out, '\n');

	return git_buf_oom(out) ? -1 : 0;
}

static int retrieve_base_commit_and_message(
	git_commit **b_commit,
	git_buf *stash_message,
	git_repository *repo)
{
	git_reference *head = NULL;
	int error;

	if ((error = retrieve_head(&head, repo)) < 0)
		return error;

	if (strcmp("HEAD", git_reference_name(head)) == 0)
86
		error = git_buf_puts(stash_message, "(no branch): ");
nulltoken committed
87
	else
88
		error = git_buf_printf(
nulltoken committed
89 90 91
			stash_message,
			"%s: ",
			git_reference_name(head) + strlen(GIT_REFS_HEADS_DIR));
92
	if (error < 0)
nulltoken committed
93 94
		goto cleanup;

95 96
	if ((error = git_commit_lookup(
			 b_commit, repo, git_reference_target(head))) < 0)
nulltoken committed
97 98
		goto cleanup;

99 100
	if ((error = append_commit_description(stash_message, *b_commit)) < 0)
		goto cleanup;
nulltoken committed
101 102 103 104 105 106

cleanup:
	git_reference_free(head);
	return error;
}

107 108 109 110
static int build_tree_from_index(
	git_tree **out,
	git_repository *repo,
	git_index *index)
nulltoken committed
111
{
112
	int error;
nulltoken committed
113 114
	git_oid i_tree_oid;

115
	if ((error = git_index_write_tree_to(&i_tree_oid, index, repo)) < 0)
116
		return error;
nulltoken committed
117

118
	return git_tree_lookup(out, repo, &i_tree_oid);
nulltoken committed
119 120 121 122
}

static int commit_index(
	git_commit **i_commit,
123
	git_repository *repo,
nulltoken committed
124
	git_index *index,
125
	const git_signature *stasher,
nulltoken committed
126 127 128 129 130 131
	const char *message,
	const git_commit *parent)
{
	git_tree *i_tree = NULL;
	git_oid i_commit_oid;
	git_buf msg = GIT_BUF_INIT;
132
	int error;
nulltoken committed
133

134
	if ((error = build_tree_from_index(&i_tree, repo, index)) < 0)
nulltoken committed
135 136
		goto cleanup;

137
	if ((error = git_buf_printf(&msg, "index on %s\n", message)) < 0)
nulltoken committed
138 139
		goto cleanup;

140
	if ((error = git_commit_create(
nulltoken committed
141 142 143 144 145 146 147 148 149
		&i_commit_oid,
		git_index_owner(index),
		NULL,
		stasher,
		stasher,
		NULL,
		git_buf_cstr(&msg),
		i_tree,
		1,
150 151
		&parent)) < 0)
		goto cleanup;
nulltoken committed
152 153 154 155 156

	error = git_commit_lookup(i_commit, git_index_owner(index), &i_commit_oid);

cleanup:
	git_tree_free(i_tree);
157
	git_buf_dispose(&msg);
nulltoken committed
158 159 160
	return error;
}

Russell Belfer committed
161
struct stash_update_rules {
nulltoken committed
162 163 164 165 166
	bool include_changed;
	bool include_untracked;
	bool include_ignored;
};

167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
/*
 * Similar to git_index_add_bypath but able to operate on any
 * index without making assumptions about the repository's index
 */
static int stash_to_index(
	git_repository *repo,
	git_index *index,
	const char *path)
{
	git_index *repo_index;
	git_index_entry entry = {{0}};
	struct stat st;
	int error;

	if (!git_repository_is_bare(repo) &&
	    (error = git_repository_index__weakptr(&repo_index, repo)) < 0)
		return error;

	if ((error = git_blob__create_from_paths(
	    &entry.id, &st, repo, NULL, path, 0, true)) < 0)
		return error;

	git_index_entry__init_from_stat(&entry, &st,
		(repo_index != NULL || !repo_index->distrust_filemode));

	entry.path = path;

	return git_index_add(index, &entry);
}

Russell Belfer committed
197
static int stash_update_index_from_diff(
198
	git_repository *repo,
Russell Belfer committed
199 200 201
	git_index *index,
	const git_diff *diff,
	struct stash_update_rules *data)
nulltoken committed
202
{
Russell Belfer committed
203 204 205 206 207 208 209 210 211 212 213 214 215 216
	int error = 0;
	size_t d, max_d = git_diff_num_deltas(diff);

	for (d = 0; !error && d < max_d; ++d) {
		const char *add_path = NULL;
		const git_diff_delta *delta = git_diff_get_delta(diff, d);

		switch (delta->status) {
		case GIT_DELTA_IGNORED:
			if (data->include_ignored)
				add_path = delta->new_file.path;
			break;

		case GIT_DELTA_UNTRACKED:
217 218
			if (data->include_untracked &&
				delta->new_file.mode != GIT_FILEMODE_TREE)
Russell Belfer committed
219
				add_path = delta->new_file.path;
nulltoken committed
220 221
			break;

Russell Belfer committed
222 223 224 225 226
		case GIT_DELTA_ADDED:
		case GIT_DELTA_MODIFIED:
			if (data->include_changed)
				add_path = delta->new_file.path;
			break;
227

Russell Belfer committed
228 229 230 231 232 233 234 235
		case GIT_DELTA_DELETED:
			if (data->include_changed &&
				!git_index_find(NULL, index, delta->old_file.path))
				error = git_index_remove(index, delta->old_file.path, 0);
			break;

		default:
			/* Unimplemented */
236 237
			git_error_set(
				GIT_ERROR_INVALID,
238
				"cannot update index. Unimplemented status (%d)",
Russell Belfer committed
239 240 241 242 243
				delta->status);
			return -1;
		}

		if (add_path != NULL)
244
			error = stash_to_index(repo, index, add_path);
Russell Belfer committed
245 246 247
	}

	return error;
nulltoken committed
248 249 250 251
}

static int build_untracked_tree(
	git_tree **tree_out,
252
	git_repository *repo,
nulltoken committed
253 254 255
	git_commit *i_commit,
	uint32_t flags)
{
256
	git_index *i_index = NULL;
nulltoken committed
257
	git_tree *i_tree = NULL;
258
	git_diff *diff = NULL;
259
	git_diff_options opts = GIT_DIFF_OPTIONS_INIT;
Russell Belfer committed
260
	struct stash_update_rules data = {0};
261
	int error;
nulltoken committed
262

263 264
	if ((error = git_index_new(&i_index)) < 0)
		goto cleanup;
nulltoken committed
265 266

	if (flags & GIT_STASH_INCLUDE_UNTRACKED) {
267 268
		opts.flags |= GIT_DIFF_INCLUDE_UNTRACKED |
			GIT_DIFF_RECURSE_UNTRACKED_DIRS;
nulltoken committed
269 270 271 272
		data.include_untracked = true;
	}

	if (flags & GIT_STASH_INCLUDE_IGNORED) {
273 274
		opts.flags |= GIT_DIFF_INCLUDE_IGNORED |
			GIT_DIFF_RECURSE_IGNORED_DIRS;
nulltoken committed
275 276 277
		data.include_ignored = true;
	}

278
	if ((error = git_commit_tree(&i_tree, i_commit)) < 0)
nulltoken committed
279 280
		goto cleanup;

281
	if ((error = git_diff_tree_to_workdir(&diff, repo, i_tree, &opts)) < 0)
nulltoken committed
282 283
		goto cleanup;

284
	if ((error = stash_update_index_from_diff(repo, i_index, diff, &data)) < 0)
nulltoken committed
285 286
		goto cleanup;

287
	error = build_tree_from_index(tree_out, repo, i_index);
nulltoken committed
288 289

cleanup:
290
	git_diff_free(diff);
nulltoken committed
291
	git_tree_free(i_tree);
292
	git_index_free(i_index);
nulltoken committed
293 294 295 296 297
	return error;
}

static int commit_untracked(
	git_commit **u_commit,
298
	git_repository *repo,
299
	const git_signature *stasher,
nulltoken committed
300 301 302 303 304 305 306
	const char *message,
	git_commit *i_commit,
	uint32_t flags)
{
	git_tree *u_tree = NULL;
	git_oid u_commit_oid;
	git_buf msg = GIT_BUF_INIT;
307
	int error;
nulltoken committed
308

309
	if ((error = build_untracked_tree(&u_tree, repo, i_commit, flags)) < 0)
nulltoken committed
310 311
		goto cleanup;

312
	if ((error = git_buf_printf(&msg, "untracked files on %s\n", message)) < 0)
nulltoken committed
313 314
		goto cleanup;

315
	if ((error = git_commit_create(
nulltoken committed
316
		&u_commit_oid,
317
		repo,
nulltoken committed
318 319 320 321 322 323 324
		NULL,
		stasher,
		stasher,
		NULL,
		git_buf_cstr(&msg),
		u_tree,
		0,
325 326
		NULL)) < 0)
		goto cleanup;
nulltoken committed
327

328
	error = git_commit_lookup(u_commit, repo, &u_commit_oid);
nulltoken committed
329 330 331

cleanup:
	git_tree_free(u_tree);
332
	git_buf_dispose(&msg);
nulltoken committed
333 334 335
	return error;
}

336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
static git_diff_delta *stash_delta_merge(
	const git_diff_delta *a,
	const git_diff_delta *b,
	git_pool *pool)
{
	/* Special case for stash: if a file is deleted in the index, but exists
	 * in the working tree, we need to stash the workdir copy for the workdir.
	 */
	if (a->status == GIT_DELTA_DELETED && b->status == GIT_DELTA_UNTRACKED) {
		git_diff_delta *dup = git_diff__delta_dup(b, pool);

		if (dup)
			dup->status = GIT_DELTA_MODIFIED;
		return dup;
	}

	return git_diff__merge_like_cgit(a, b, pool);
}

nulltoken committed
355 356
static int build_workdir_tree(
	git_tree **tree_out,
357 358
	git_repository *repo,
	git_index *i_index,
nulltoken committed
359 360 361
	git_commit *b_commit)
{
	git_tree *b_tree = NULL;
362
	git_diff *diff = NULL, *idx_to_wd = NULL;
363
	git_diff_options opts = GIT_DIFF_OPTIONS_INIT;
Russell Belfer committed
364
	struct stash_update_rules data = {0};
365
	int error;
nulltoken committed
366

367
	opts.flags = GIT_DIFF_IGNORE_SUBMODULES | GIT_DIFF_INCLUDE_UNTRACKED;
368

369
	if ((error = git_commit_tree(&b_tree, b_commit)) < 0)
nulltoken committed
370 371
		goto cleanup;

372 373
	if ((error = git_diff_tree_to_index(&diff, repo, b_tree, i_index, &opts)) < 0 ||
		(error = git_diff_index_to_workdir(&idx_to_wd, repo, i_index, &opts)) < 0 ||
374
		(error = git_diff__merge(diff, idx_to_wd, stash_delta_merge)) < 0)
nulltoken committed
375 376 377 378
		goto cleanup;

	data.include_changed = true;

379
	if ((error = stash_update_index_from_diff(repo, i_index, diff, &data)) < 0)
nulltoken committed
380 381
		goto cleanup;

382
	error = build_tree_from_index(tree_out, repo, i_index);
nulltoken committed
383 384

cleanup:
385
	git_diff_free(idx_to_wd);
386
	git_diff_free(diff);
nulltoken committed
387
	git_tree_free(b_tree);
388

nulltoken committed
389 390 391 392 393
	return error;
}

static int commit_worktree(
	git_oid *w_commit_oid,
394
	git_repository *repo,
395
	const git_signature *stasher,
nulltoken committed
396 397 398 399 400
	const char *message,
	git_commit *i_commit,
	git_commit *b_commit,
	git_commit *u_commit)
{
401
	int error = 0;
nulltoken committed
402
	git_tree *w_tree = NULL, *i_tree = NULL;
403
	git_index *i_index = NULL;
nulltoken committed
404
	const git_commit *parents[] = {	NULL, NULL,	NULL };
405
	int ignorecase;
nulltoken committed
406 407 408 409 410

	parents[0] = b_commit;
	parents[1] = i_commit;
	parents[2] = u_commit;

411 412
	if ((error = git_commit_tree(&i_tree, i_commit)) < 0)
		goto cleanup;
nulltoken committed
413

414 415 416 417 418 419 420
	if ((error = git_index_new(&i_index)) < 0 ||
		(error = git_repository__cvar(&ignorecase, repo, GIT_CVAR_IGNORECASE)) < 0)
		goto cleanup;

	git_index__set_ignore_case(i_index, ignorecase);

	if ((error = git_index_read_tree(i_index, i_tree)) < 0)
nulltoken committed
421 422
		goto cleanup;

423
	if ((error = build_workdir_tree(&w_tree, repo, i_index, b_commit)) < 0)
nulltoken committed
424 425
		goto cleanup;

426
	error = git_commit_create(
nulltoken committed
427
		w_commit_oid,
428
		repo,
nulltoken committed
429 430 431 432 433 434
		NULL,
		stasher,
		stasher,
		NULL,
		message,
		w_tree,
435 436
		u_commit ? 3 : 2,
		parents);
nulltoken committed
437 438 439 440

cleanup:
	git_tree_free(i_tree);
	git_tree_free(w_tree);
441
	git_index_free(i_index);
nulltoken committed
442 443 444 445 446 447 448 449
	return error;
}

static int prepare_worktree_commit_message(
	git_buf* msg,
	const char *user_message)
{
	git_buf buf = GIT_BUF_INIT;
450 451
	int error;

452 453
	if ((error = git_buf_set(&buf, git_buf_cstr(msg), git_buf_len(msg))) < 0)
		return error;
nulltoken committed
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469

	git_buf_clear(msg);

	if (!user_message)
		git_buf_printf(msg, "WIP on %s", git_buf_cstr(&buf));
	else {
		const char *colon;

		if ((colon = strchr(git_buf_cstr(&buf), ':')) == NULL)
			goto cleanup;

		git_buf_puts(msg, "On ");
		git_buf_put(msg, git_buf_cstr(&buf), colon - buf.ptr);
		git_buf_printf(msg, ": %s\n", user_message);
	}

470
	error = (git_buf_oom(msg) || git_buf_oom(&buf)) ? -1 : 0;
nulltoken committed
471 472

cleanup:
473
	git_buf_dispose(&buf);
474

nulltoken committed
475 476 477 478 479 480 481 482
	return error;
}

static int update_reflog(
	git_oid *w_commit_oid,
	git_repository *repo,
	const char *message)
{
483
	git_reference *stash;
nulltoken committed
484 485
	int error;

486 487
	if ((error = git_reference_ensure_log(repo, GIT_REFS_STASH_FILE)) < 0)
		return error;
nulltoken committed
488

489
	error = git_reference_create(&stash, repo, GIT_REFS_STASH_FILE, w_commit_oid, 1, message);
nulltoken committed
490

491
	git_reference_free(stash);
nulltoken committed
492 493 494 495 496 497 498 499 500 501

	return error;
}

static int is_dirty_cb(const char *path, unsigned int status, void *payload)
{
	GIT_UNUSED(path);
	GIT_UNUSED(status);
	GIT_UNUSED(payload);

502
	return GIT_PASSTHROUGH;
nulltoken committed
503 504 505 506 507 508 509 510
}

static int ensure_there_are_changes_to_stash(
	git_repository *repo,
	bool include_untracked_files,
	bool include_ignored_files)
{
	int error;
511
	git_status_options opts = GIT_STATUS_OPTIONS_INIT;
nulltoken committed
512 513

	opts.show  = GIT_STATUS_SHOW_INDEX_AND_WORKDIR;
514 515
	opts.flags = GIT_STATUS_OPT_EXCLUDE_SUBMODULES;

nulltoken committed
516
	if (include_untracked_files)
517
		opts.flags |= GIT_STATUS_OPT_INCLUDE_UNTRACKED |
518
			GIT_STATUS_OPT_RECURSE_UNTRACKED_DIRS;
nulltoken committed
519 520

	if (include_ignored_files)
521 522
		opts.flags |= GIT_STATUS_OPT_INCLUDE_IGNORED |
			GIT_STATUS_OPT_RECURSE_IGNORED_DIRS;
nulltoken committed
523 524 525

	error = git_status_foreach_ext(repo, &opts, is_dirty_cb, NULL);

526
	if (error == GIT_PASSTHROUGH)
nulltoken committed
527 528 529
		return 0;

	if (!error)
530
		return create_error(GIT_ENOTFOUND, "there is nothing to stash.");
nulltoken committed
531 532 533 534 535 536 537

	return error;
}

static int reset_index_and_workdir(
	git_repository *repo,
	git_commit *commit,
538 539
	bool remove_untracked,
	bool remove_ignored)
nulltoken committed
540
{
541
	git_checkout_options opts = GIT_CHECKOUT_OPTIONS_INIT;
nulltoken committed
542

543
	opts.checkout_strategy = GIT_CHECKOUT_FORCE;
nulltoken committed
544 545 546 547

	if (remove_untracked)
		opts.checkout_strategy |= GIT_CHECKOUT_REMOVE_UNTRACKED;

548 549 550
	if (remove_ignored)
		opts.checkout_strategy |= GIT_CHECKOUT_REMOVE_IGNORED;

nulltoken committed
551 552 553 554 555 556
	return git_checkout_tree(repo, (git_object *)commit, &opts);
}

int git_stash_save(
	git_oid *out,
	git_repository *repo,
557
	const git_signature *stasher,
nulltoken committed
558 559 560 561 562 563 564 565 566 567
	const char *message,
	uint32_t flags)
{
	git_index *index = NULL;
	git_commit *b_commit = NULL, *i_commit = NULL, *u_commit = NULL;
	git_buf msg = GIT_BUF_INIT;
	int error;

	assert(out && repo && stasher);

568
	if ((error = git_repository__ensure_not_bare(repo, "stash save")) < 0)
nulltoken committed
569 570 571 572 573 574 575
		return error;

	if ((error = retrieve_base_commit_and_message(&b_commit, &msg, repo)) < 0)
		goto cleanup;

	if ((error = ensure_there_are_changes_to_stash(
		repo,
576 577
		(flags & GIT_STASH_INCLUDE_UNTRACKED) != 0,
		(flags & GIT_STASH_INCLUDE_IGNORED) != 0)) < 0)
nulltoken committed
578 579
		goto cleanup;

580
	if ((error = git_repository_index(&index, repo)) < 0)
nulltoken committed
581 582
		goto cleanup;

583
	if ((error = commit_index(
584
			&i_commit, repo, index, stasher, git_buf_cstr(&msg), b_commit)) < 0)
nulltoken committed
585 586
		goto cleanup;

587 588
	if ((flags & (GIT_STASH_INCLUDE_UNTRACKED | GIT_STASH_INCLUDE_IGNORED)) &&
		(error = commit_untracked(
589
			&u_commit, repo, stasher, git_buf_cstr(&msg),
590
			i_commit, flags)) < 0)
nulltoken committed
591 592
		goto cleanup;

593
	if ((error = prepare_worktree_commit_message(&msg, message)) < 0)
nulltoken committed
594 595
		goto cleanup;

596
	if ((error = commit_worktree(
597
			out, repo, stasher, git_buf_cstr(&msg),
598
			i_commit, b_commit, u_commit)) < 0)
nulltoken committed
599 600 601
		goto cleanup;

	git_buf_rtrim(&msg);
602

603
	if ((error = update_reflog(out, repo, git_buf_cstr(&msg))) < 0)
nulltoken committed
604 605
		goto cleanup;

606
	if ((error = reset_index_and_workdir(
nulltoken committed
607
		repo,
608
		((flags & GIT_STASH_KEEP_INDEX) != 0) ? i_commit : b_commit,
609 610
		(flags & GIT_STASH_INCLUDE_UNTRACKED) != 0,
		(flags & GIT_STASH_INCLUDE_IGNORED) != 0)) < 0)
nulltoken committed
611 612 613
		goto cleanup;

cleanup:
614

615
	git_buf_dispose(&msg);
nulltoken committed
616 617 618 619
	git_commit_free(i_commit);
	git_commit_free(b_commit);
	git_commit_free(u_commit);
	git_index_free(index);
620

nulltoken committed
621 622
	return error;
}
623

624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
static int retrieve_stash_commit(
	git_commit **commit,
	git_repository *repo,
	size_t index)
{
	git_reference *stash = NULL;
	git_reflog *reflog = NULL;
	int error;
	size_t max;
	const git_reflog_entry *entry;

	if ((error = git_reference_lookup(&stash, repo, GIT_REFS_STASH_FILE)) < 0)
		goto cleanup;

	if ((error = git_reflog_read(&reflog, repo, GIT_REFS_STASH_FILE)) < 0)
		goto cleanup;

	max = git_reflog_entrycount(reflog);
642
	if (!max || index > max - 1) {
643
		error = GIT_ENOTFOUND;
644
		git_error_set(GIT_ERROR_STASH, "no stashed state at position %" PRIuZ, index);
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 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 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
		goto cleanup;
	}

	entry = git_reflog_entry_byindex(reflog, index);
	if ((error = git_commit_lookup(commit, repo, git_reflog_entry_id_new(entry))) < 0)
		goto cleanup;

cleanup:
	git_reference_free(stash);
	git_reflog_free(reflog);
	return error;
}

static int retrieve_stash_trees(
	git_tree **out_stash_tree,
	git_tree **out_base_tree,
	git_tree **out_index_tree,
	git_tree **out_index_parent_tree,
	git_tree **out_untracked_tree,
	git_commit *stash_commit)
{
	git_tree *stash_tree = NULL;
	git_commit *base_commit = NULL;
	git_tree *base_tree = NULL;
	git_commit *index_commit = NULL;
	git_tree *index_tree = NULL;
	git_commit *index_parent_commit = NULL;
	git_tree *index_parent_tree = NULL;
	git_commit *untracked_commit = NULL;
	git_tree *untracked_tree = NULL;
	int error;

	if ((error = git_commit_tree(&stash_tree, stash_commit)) < 0)
		goto cleanup;

	if ((error = git_commit_parent(&base_commit, stash_commit, 0)) < 0)
		goto cleanup;
	if ((error = git_commit_tree(&base_tree, base_commit)) < 0)
		goto cleanup;

	if ((error = git_commit_parent(&index_commit, stash_commit, 1)) < 0)
		goto cleanup;
	if ((error = git_commit_tree(&index_tree, index_commit)) < 0)
		goto cleanup;

	if ((error = git_commit_parent(&index_parent_commit, index_commit, 0)) < 0)
		goto cleanup;
	if ((error = git_commit_tree(&index_parent_tree, index_parent_commit)) < 0)
		goto cleanup;

	if (git_commit_parentcount(stash_commit) == 3) {
		if ((error = git_commit_parent(&untracked_commit, stash_commit, 2)) < 0)
			goto cleanup;
		if ((error = git_commit_tree(&untracked_tree, untracked_commit)) < 0)
			goto cleanup;
	}

	*out_stash_tree = stash_tree;
	*out_base_tree = base_tree;
	*out_index_tree = index_tree;
	*out_index_parent_tree = index_parent_tree;
	*out_untracked_tree = untracked_tree;

cleanup:
	git_commit_free(untracked_commit);
	git_commit_free(index_parent_commit);
	git_commit_free(index_commit);
	git_commit_free(base_commit);
	if (error < 0) {
		git_tree_free(stash_tree);
		git_tree_free(base_tree);
		git_tree_free(index_tree);
		git_tree_free(index_parent_tree);
		git_tree_free(untracked_tree);
	}
	return error;
}

723 724 725 726 727 728 729 730
static int merge_indexes(
	git_index **out,
	git_repository *repo,
	git_tree *ancestor_tree,
	git_index *ours_index,
	git_index *theirs_index)
{
	git_iterator *ancestor = NULL, *ours = NULL, *theirs = NULL;
731
	git_iterator_options iter_opts = GIT_ITERATOR_OPTIONS_INIT;
732 733
	int error;

734 735 736
	iter_opts.flags = GIT_ITERATOR_DONT_IGNORE_CASE;

	if ((error = git_iterator_for_tree(&ancestor, ancestor_tree, &iter_opts)) < 0 ||
737 738
		(error = git_iterator_for_index(&ours, repo, ours_index, &iter_opts)) < 0 ||
		(error = git_iterator_for_index(&theirs, repo, theirs_index, &iter_opts)) < 0)
739 740 741 742 743 744 745 746 747 748 749
		goto done;

	error = git_merge__iterators(out, repo, ancestor, ours, theirs, NULL);

done:
	git_iterator_free(ancestor);
	git_iterator_free(ours);
	git_iterator_free(theirs);
	return error;
}

750 751
static int merge_index_and_tree(
	git_index **out,
752
	git_repository *repo,
753 754 755
	git_tree *ancestor_tree,
	git_index *ours_index,
	git_tree *theirs_tree)
756
{
757
	git_iterator *ancestor = NULL, *ours = NULL, *theirs = NULL;
758
	git_iterator_options iter_opts = GIT_ITERATOR_OPTIONS_INIT;
759 760
	int error;

761 762 763
	iter_opts.flags = GIT_ITERATOR_DONT_IGNORE_CASE;

	if ((error = git_iterator_for_tree(&ancestor, ancestor_tree, &iter_opts)) < 0 ||
764
		(error = git_iterator_for_index(&ours, repo, ours_index, &iter_opts)) < 0 ||
765
		(error = git_iterator_for_tree(&theirs, theirs_tree, &iter_opts)) < 0)
766
		goto done;
767

768
	error = git_merge__iterators(out, repo, ancestor, ours, theirs, NULL);
769

770 771 772 773
done:
	git_iterator_free(ancestor);
	git_iterator_free(ours);
	git_iterator_free(theirs);
774 775 776
	return error;
}

777 778 779
static void normalize_apply_options(
	git_stash_apply_options *opts,
	const git_stash_apply_options *given_apply_opts)
780
{
781 782
	if (given_apply_opts != NULL) {
		memcpy(opts, given_apply_opts, sizeof(git_stash_apply_options));
783
	} else {
784 785
		git_stash_apply_options default_apply_opts = GIT_STASH_APPLY_OPTIONS_INIT;
		memcpy(opts, &default_apply_opts, sizeof(git_stash_apply_options));
786 787
	}

788 789
	opts->checkout_options.checkout_strategy |= GIT_CHECKOUT_NO_REFRESH;

790 791
	if (!opts->checkout_options.our_label)
		opts->checkout_options.our_label = "Updated upstream";
792

793 794 795 796 797 798 799 800 801
	if (!opts->checkout_options.their_label)
		opts->checkout_options.their_label = "Stashed changes";
}

int git_stash_apply_init_options(git_stash_apply_options *opts, unsigned int version)
{
	GIT_INIT_STRUCTURE_FROM_TEMPLATE(
		opts, version, git_stash_apply_options, GIT_STASH_APPLY_OPTIONS_INIT);
	return 0;
802 803
}

Carlos Martín Nieto committed
804 805 806 807 808 809 810 811
#define NOTIFY_PROGRESS(opts, progress_type)				\
	do {								\
		if ((opts).progress_cb &&				\
		    (error = (opts).progress_cb((progress_type), (opts).progress_payload))) { \
			error = (error < 0) ? error : -1;		\
			goto cleanup;					\
		}							\
	} while(false);
812

813 814 815 816 817 818 819 820 821 822 823 824
static int ensure_clean_index(git_repository *repo, git_index *index)
{
	git_tree *head_tree = NULL;
	git_diff *index_diff = NULL;
	int error = 0;

	if ((error = git_repository_head_tree(&head_tree, repo)) < 0 ||
		(error = git_diff_tree_to_index(
			&index_diff, repo, head_tree, index, NULL)) < 0)
		goto done;

	if (git_diff_num_deltas(index_diff) > 0) {
825
		git_error_set(GIT_ERROR_STASH, "%" PRIuZ " uncommitted changes exist in the index",
826 827 828 829 830 831 832 833 834 835
			git_diff_num_deltas(index_diff));
		error = GIT_EUNCOMMITTED;
	}

done:
	git_diff_free(index_diff);
	git_tree_free(head_tree);
	return error;
}

836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
static int stage_new_file(const git_index_entry **entries, void *data)
{
	git_index *index = data;

	if(entries[0] == NULL)
		return git_index_add(index, entries[1]);
	else
		return git_index_add(index, entries[0]);
}

static int stage_new_files(
	git_index **out,
	git_tree *parent_tree,
	git_tree *tree)
{
	git_iterator *iterators[2] = { NULL, NULL };
852
	git_iterator_options iterator_options = GIT_ITERATOR_OPTIONS_INIT;
853 854 855 856
	git_index *index = NULL;
	int error;

	if ((error = git_index_new(&index)) < 0 ||
857 858 859 860
		(error = git_iterator_for_tree(
			&iterators[0], parent_tree, &iterator_options)) < 0 ||
		(error = git_iterator_for_tree(
			&iterators[1], tree, &iterator_options)) < 0)
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
		goto done;

	error = git_iterator_walk(iterators, 2, stage_new_file, index);

done:
	if (error < 0)
		git_index_free(index);
	else
		*out = index;

	git_iterator_free(iterators[0]);
	git_iterator_free(iterators[1]);

	return error;
}

877 878 879
int git_stash_apply(
	git_repository *repo,
	size_t index,
880
	const git_stash_apply_options *given_opts)
881
{
882
	git_stash_apply_options opts;
883
	unsigned int checkout_strategy;
884 885
	git_commit *stash_commit = NULL;
	git_tree *stash_tree = NULL;
886
	git_tree *stash_parent_tree = NULL;
887 888 889
	git_tree *index_tree = NULL;
	git_tree *index_parent_tree = NULL;
	git_tree *untracked_tree = NULL;
890
	git_index *stash_adds = NULL;
891
	git_index *repo_index = NULL;
892 893 894
	git_index *unstashed_index = NULL;
	git_index *modified_index = NULL;
	git_index *untracked_index = NULL;
895 896
	int error;

897
	GIT_ERROR_CHECK_VERSION(given_opts, GIT_STASH_APPLY_OPTIONS_VERSION, "git_stash_apply_options");
898 899 900

	normalize_apply_options(&opts, given_opts);
	checkout_strategy = opts.checkout_options.checkout_strategy;
901

902 903
	NOTIFY_PROGRESS(opts, GIT_STASH_APPLY_PROGRESS_LOADING_STASH);

904 905 906 907 908 909
	/* Retrieve commit corresponding to the given stash */
	if ((error = retrieve_stash_commit(&stash_commit, repo, index)) < 0)
		goto cleanup;

	/* Retrieve all trees in the stash */
	if ((error = retrieve_stash_trees(
910
			&stash_tree, &stash_parent_tree, &index_tree,
911 912 913 914 915 916 917
			&index_parent_tree, &untracked_tree, stash_commit)) < 0)
		goto cleanup;

	/* Load repo index */
	if ((error = git_repository_index(&repo_index, repo)) < 0)
		goto cleanup;

918 919
	NOTIFY_PROGRESS(opts, GIT_STASH_APPLY_PROGRESS_ANALYZE_INDEX);

920 921 922
	if ((error = ensure_clean_index(repo, repo_index)) < 0)
		goto cleanup;

923
	/* Restore index if required */
924
	if ((opts.flags & GIT_STASH_APPLY_REINSTATE_INDEX) &&
925
		git_oid_cmp(git_tree_id(stash_parent_tree), git_tree_id(index_tree))) {
926

927 928
		if ((error = merge_index_and_tree(
				&unstashed_index, repo, index_parent_tree, repo_index, index_tree)) < 0)
929 930
			goto cleanup;

931
		if (git_index_has_conflicts(unstashed_index)) {
932
			error = GIT_ECONFLICT;
933
			goto cleanup;
934
		}
935 936 937 938 939 940

	/* Otherwise, stage any new files in the stash tree.  (Note: their
	 * previously unstaged contents are staged, not the previously staged.)
	 */
	} else if ((opts.flags & GIT_STASH_APPLY_REINSTATE_INDEX) == 0) {
		if ((error = stage_new_files(
941
				&stash_adds, stash_parent_tree, stash_tree)) < 0 ||
942 943 944
			(error = merge_indexes(
				&unstashed_index, repo, stash_parent_tree, repo_index, stash_adds)) < 0)
			goto cleanup;
945 946
	}

947 948
	NOTIFY_PROGRESS(opts, GIT_STASH_APPLY_PROGRESS_ANALYZE_MODIFIED);

949
	/* Restore modified files in workdir */
950 951
	if ((error = merge_index_and_tree(
			&modified_index, repo, stash_parent_tree, repo_index, stash_tree)) < 0)
952 953
		goto cleanup;

954
	/* If applicable, restore untracked / ignored files in workdir */
955 956 957 958 959 960
	if (untracked_tree) {
		NOTIFY_PROGRESS(opts, GIT_STASH_APPLY_PROGRESS_ANALYZE_UNTRACKED);

		if ((error = merge_index_and_tree(&untracked_index, repo, NULL, repo_index, untracked_tree)) < 0)
			goto cleanup;
	}
961

962
	if (untracked_index) {
963
		opts.checkout_options.checkout_strategy |= GIT_CHECKOUT_DONT_UPDATE_INDEX;
964

965 966
		NOTIFY_PROGRESS(opts, GIT_STASH_APPLY_PROGRESS_CHECKOUT_UNTRACKED);

967
		if ((error = git_checkout_index(repo, untracked_index, &opts.checkout_options)) < 0)
968 969
			goto cleanup;

970
		opts.checkout_options.checkout_strategy = checkout_strategy;
971 972 973 974 975 976 977 978 979
	}


	/* If there are conflicts in the modified index, then we need to actually
	 * check that out as the repo's index.  Otherwise, we don't update the
	 * index.
	 */

	if (!git_index_has_conflicts(modified_index))
980
		opts.checkout_options.checkout_strategy |= GIT_CHECKOUT_DONT_UPDATE_INDEX;
981 982 983 984 985

	/* Check out the modified index using the existing repo index as baseline,
	 * so that existing modifications in the index can be rewritten even when
	 * checking out safely.
	 */
986
	opts.checkout_options.baseline_index = repo_index;
987

988 989
	NOTIFY_PROGRESS(opts, GIT_STASH_APPLY_PROGRESS_CHECKOUT_MODIFIED);

990
	if ((error = git_checkout_index(repo, modified_index, &opts.checkout_options)) < 0)
991 992
		goto cleanup;

993 994 995 996 997
	if (unstashed_index && !git_index_has_conflicts(modified_index)) {
		if ((error = git_index_read_index(repo_index, unstashed_index)) < 0)
			goto cleanup;
	}

998 999
	NOTIFY_PROGRESS(opts, GIT_STASH_APPLY_PROGRESS_DONE);

1000 1001
	error = git_index_write(repo_index);

1002
cleanup:
1003 1004 1005
	git_index_free(untracked_index);
	git_index_free(modified_index);
	git_index_free(unstashed_index);
1006
	git_index_free(stash_adds);
1007 1008 1009 1010
	git_index_free(repo_index);
	git_tree_free(untracked_tree);
	git_tree_free(index_parent_tree);
	git_tree_free(index_tree);
1011
	git_tree_free(stash_parent_tree);
1012 1013 1014 1015 1016
	git_tree_free(stash_tree);
	git_commit_free(stash_commit);
	return error;
}

1017 1018
int git_stash_foreach(
	git_repository *repo,
Ben Straub committed
1019
	git_stash_cb callback,
1020 1021 1022 1023 1024 1025 1026 1027 1028
	void *payload)
{
	git_reference *stash;
	git_reflog *reflog = NULL;
	int error;
	size_t i, max;
	const git_reflog_entry *entry;

	error = git_reference_lookup(&stash, repo, GIT_REFS_STASH_FILE);
1029
	if (error == GIT_ENOTFOUND) {
1030
		git_error_clear();
1031
		return 0;
1032
	}
1033 1034 1035
	if (error < 0)
		goto cleanup;

1036
	if ((error = git_reflog_read(&reflog, repo, GIT_REFS_STASH_FILE)) < 0)
1037 1038 1039 1040
		goto cleanup;

	max = git_reflog_entrycount(reflog);
	for (i = 0; i < max; i++) {
1041
		entry = git_reflog_entry_byindex(reflog, i);
1042

1043 1044 1045 1046 1047 1048
		error = callback(i,
			git_reflog_entry_message(entry),
			git_reflog_entry_id_new(entry),
			payload);

		if (error) {
1049
			git_error_set_after_callback(error);
1050
			break;
1051
		}
1052 1053 1054 1055 1056 1057 1058
	}

cleanup:
	git_reference_free(stash);
	git_reflog_free(reflog);
	return error;
}
nulltoken committed
1059 1060 1061 1062 1063

int git_stash_drop(
	git_repository *repo,
	size_t index)
{
1064 1065
	git_transaction *tx;
	git_reference *stash = NULL;
nulltoken committed
1066 1067 1068 1069
	git_reflog *reflog = NULL;
	size_t max;
	int error;

1070
	if ((error = git_transaction_new(&tx, repo)) < 0)
nulltoken committed
1071 1072
		return error;

1073
	if ((error = git_transaction_lock_ref(tx, GIT_REFS_STASH_FILE)) < 0)
1074 1075 1076 1077 1078
		goto cleanup;

	if ((error = git_reference_lookup(&stash, repo, GIT_REFS_STASH_FILE)) < 0)
		goto cleanup;

1079
	if ((error = git_reflog_read(&reflog, repo, GIT_REFS_STASH_FILE)) < 0)
nulltoken committed
1080 1081 1082 1083
		goto cleanup;

	max = git_reflog_entrycount(reflog);

1084
	if (!max || index > max - 1) {
nulltoken committed
1085
		error = GIT_ENOTFOUND;
1086
		git_error_set(GIT_ERROR_STASH, "no stashed state at position %" PRIuZ, index);
nulltoken committed
1087 1088 1089
		goto cleanup;
	}

1090
	if ((error = git_reflog_drop(reflog, index, true)) < 0)
nulltoken committed
1091 1092
		goto cleanup;

1093
	if ((error = git_transaction_set_reflog(tx, GIT_REFS_STASH_FILE, reflog)) < 0)
nulltoken committed
1094 1095 1096
		goto cleanup;

	if (max == 1) {
1097 1098
		if ((error = git_transaction_remove(tx, GIT_REFS_STASH_FILE)) < 0)
			goto cleanup;
1099 1100 1101 1102
	} else if (index == 0) {
		const git_reflog_entry *entry;

		entry = git_reflog_entry_byindex(reflog, 0);
1103
		if ((error = git_transaction_set_target(tx, GIT_REFS_STASH_FILE, &entry->oid_cur, NULL, NULL)) < 0)
1104
			goto cleanup;
nulltoken committed
1105 1106
	}

1107 1108
	error = git_transaction_commit(tx);

nulltoken committed
1109 1110
cleanup:
	git_reference_free(stash);
1111
	git_transaction_free(tx);
nulltoken committed
1112 1113 1114
	git_reflog_free(reflog);
	return error;
}
1115 1116 1117 1118

int git_stash_pop(
	git_repository *repo,
	size_t index,
1119
	const git_stash_apply_options *options)
1120 1121 1122
{
	int error;

1123
	if ((error = git_stash_apply(repo, index, options)) < 0)
1124 1125 1126 1127
		return error;

	return git_stash_drop(repo, index);
}