1 /*
2  * Copyright (C) the libgit2 contributors. All rights reserved.
3  *
4  * This file is part of libgit2, distributed under the GNU GPL v2 with
5  * a Linking Exception. For full terms see the included COPYING file.
6  */
7 
8 #include "common.h"
9 
10 #include "repository.h"
11 #include "commit.h"
12 #include "message.h"
13 #include "tree.h"
14 #include "reflog.h"
15 #include "blob.h"
16 #include "git2/diff.h"
17 #include "git2/stash.h"
18 #include "git2/status.h"
19 #include "git2/checkout.h"
20 #include "git2/index.h"
21 #include "git2/transaction.h"
22 #include "git2/merge.h"
23 #include "index.h"
24 #include "signature.h"
25 #include "iterator.h"
26 #include "merge.h"
27 #include "diff.h"
28 #include "diff_generate.h"
29 
create_error(int error,const char * msg)30 static int create_error(int error, const char *msg)
31 {
32 	git_error_set(GIT_ERROR_STASH, "cannot stash changes - %s", msg);
33 	return error;
34 }
35 
retrieve_head(git_reference ** out,git_repository * repo)36 static int retrieve_head(git_reference **out, git_repository *repo)
37 {
38 	int error = git_repository_head(out, repo);
39 
40 	if (error == GIT_EUNBORNBRANCH)
41 		return create_error(error, "you do not have the initial commit yet.");
42 
43 	return error;
44 }
45 
append_abbreviated_oid(git_buf * out,const git_oid * b_commit)46 static int append_abbreviated_oid(git_buf *out, const git_oid *b_commit)
47 {
48 	char *formatted_oid;
49 
50 	formatted_oid = git_oid_allocfmt(b_commit);
51 	GIT_ERROR_CHECK_ALLOC(formatted_oid);
52 
53 	git_buf_put(out, formatted_oid, 7);
54 	git__free(formatted_oid);
55 
56 	return git_buf_oom(out) ? -1 : 0;
57 }
58 
append_commit_description(git_buf * out,git_commit * commit)59 static int append_commit_description(git_buf *out, git_commit* commit)
60 {
61 	const char *summary = git_commit_summary(commit);
62 	GIT_ERROR_CHECK_ALLOC(summary);
63 
64 	if (append_abbreviated_oid(out, git_commit_id(commit)) < 0)
65 		return -1;
66 
67 	git_buf_putc(out, ' ');
68 	git_buf_puts(out, summary);
69 	git_buf_putc(out, '\n');
70 
71 	return git_buf_oom(out) ? -1 : 0;
72 }
73 
retrieve_base_commit_and_message(git_commit ** b_commit,git_buf * stash_message,git_repository * repo)74 static int retrieve_base_commit_and_message(
75 	git_commit **b_commit,
76 	git_buf *stash_message,
77 	git_repository *repo)
78 {
79 	git_reference *head = NULL;
80 	int error;
81 
82 	if ((error = retrieve_head(&head, repo)) < 0)
83 		return error;
84 
85 	if (strcmp("HEAD", git_reference_name(head)) == 0)
86 		error = git_buf_puts(stash_message, "(no branch): ");
87 	else
88 		error = git_buf_printf(
89 			stash_message,
90 			"%s: ",
91 			git_reference_name(head) + strlen(GIT_REFS_HEADS_DIR));
92 	if (error < 0)
93 		goto cleanup;
94 
95 	if ((error = git_commit_lookup(
96 			 b_commit, repo, git_reference_target(head))) < 0)
97 		goto cleanup;
98 
99 	if ((error = append_commit_description(stash_message, *b_commit)) < 0)
100 		goto cleanup;
101 
102 cleanup:
103 	git_reference_free(head);
104 	return error;
105 }
106 
build_tree_from_index(git_tree ** out,git_repository * repo,git_index * index)107 static int build_tree_from_index(
108 	git_tree **out,
109 	git_repository *repo,
110 	git_index *index)
111 {
112 	int error;
113 	git_oid i_tree_oid;
114 
115 	if ((error = git_index_write_tree_to(&i_tree_oid, index, repo)) < 0)
116 		return error;
117 
118 	return git_tree_lookup(out, repo, &i_tree_oid);
119 }
120 
commit_index(git_commit ** i_commit,git_repository * repo,git_index * index,const git_signature * stasher,const char * message,const git_commit * parent)121 static int commit_index(
122 	git_commit **i_commit,
123 	git_repository *repo,
124 	git_index *index,
125 	const git_signature *stasher,
126 	const char *message,
127 	const git_commit *parent)
128 {
129 	git_tree *i_tree = NULL;
130 	git_oid i_commit_oid;
131 	git_buf msg = GIT_BUF_INIT;
132 	int error;
133 
134 	if ((error = build_tree_from_index(&i_tree, repo, index)) < 0)
135 		goto cleanup;
136 
137 	if ((error = git_buf_printf(&msg, "index on %s\n", message)) < 0)
138 		goto cleanup;
139 
140 	if ((error = git_commit_create(
141 		&i_commit_oid,
142 		git_index_owner(index),
143 		NULL,
144 		stasher,
145 		stasher,
146 		NULL,
147 		git_buf_cstr(&msg),
148 		i_tree,
149 		1,
150 		&parent)) < 0)
151 		goto cleanup;
152 
153 	error = git_commit_lookup(i_commit, git_index_owner(index), &i_commit_oid);
154 
155 cleanup:
156 	git_tree_free(i_tree);
157 	git_buf_dispose(&msg);
158 	return error;
159 }
160 
161 struct stash_update_rules {
162 	bool include_changed;
163 	bool include_untracked;
164 	bool include_ignored;
165 };
166 
167 /*
168  * Similar to git_index_add_bypath but able to operate on any
169  * index without making assumptions about the repository's index
170  */
stash_to_index(git_repository * repo,git_index * index,const char * path)171 static int stash_to_index(
172 	git_repository *repo,
173 	git_index *index,
174 	const char *path)
175 {
176 	git_index *repo_index;
177 	git_index_entry entry = {{0}};
178 	struct stat st;
179 	int error;
180 
181 	if (!git_repository_is_bare(repo) &&
182 	    (error = git_repository_index__weakptr(&repo_index, repo)) < 0)
183 		return error;
184 
185 	if ((error = git_blob__create_from_paths(
186 	    &entry.id, &st, repo, NULL, path, 0, true)) < 0)
187 		return error;
188 
189 	git_index_entry__init_from_stat(&entry, &st,
190 		(repo_index != NULL || !repo_index->distrust_filemode));
191 
192 	entry.path = path;
193 
194 	return git_index_add(index, &entry);
195 }
196 
stash_update_index_from_diff(git_repository * repo,git_index * index,const git_diff * diff,struct stash_update_rules * data)197 static int stash_update_index_from_diff(
198 	git_repository *repo,
199 	git_index *index,
200 	const git_diff *diff,
201 	struct stash_update_rules *data)
202 {
203 	int error = 0;
204 	size_t d, max_d = git_diff_num_deltas(diff);
205 
206 	for (d = 0; !error && d < max_d; ++d) {
207 		const char *add_path = NULL;
208 		const git_diff_delta *delta = git_diff_get_delta(diff, d);
209 
210 		switch (delta->status) {
211 		case GIT_DELTA_IGNORED:
212 			if (data->include_ignored)
213 				add_path = delta->new_file.path;
214 			break;
215 
216 		case GIT_DELTA_UNTRACKED:
217 			if (data->include_untracked &&
218 				delta->new_file.mode != GIT_FILEMODE_TREE)
219 				add_path = delta->new_file.path;
220 			break;
221 
222 		case GIT_DELTA_ADDED:
223 		case GIT_DELTA_MODIFIED:
224 			if (data->include_changed)
225 				add_path = delta->new_file.path;
226 			break;
227 
228 		case GIT_DELTA_DELETED:
229 			if (data->include_changed &&
230 				!git_index_find(NULL, index, delta->old_file.path))
231 				error = git_index_remove(index, delta->old_file.path, 0);
232 			break;
233 
234 		default:
235 			/* Unimplemented */
236 			git_error_set(
237 				GIT_ERROR_INVALID,
238 				"cannot update index. Unimplemented status (%d)",
239 				delta->status);
240 			return -1;
241 		}
242 
243 		if (add_path != NULL)
244 			error = stash_to_index(repo, index, add_path);
245 	}
246 
247 	return error;
248 }
249 
build_untracked_tree(git_tree ** tree_out,git_repository * repo,git_commit * i_commit,uint32_t flags)250 static int build_untracked_tree(
251 	git_tree **tree_out,
252 	git_repository *repo,
253 	git_commit *i_commit,
254 	uint32_t flags)
255 {
256 	git_index *i_index = NULL;
257 	git_tree *i_tree = NULL;
258 	git_diff *diff = NULL;
259 	git_diff_options opts = GIT_DIFF_OPTIONS_INIT;
260 	struct stash_update_rules data = {0};
261 	int error;
262 
263 	if ((error = git_index_new(&i_index)) < 0)
264 		goto cleanup;
265 
266 	if (flags & GIT_STASH_INCLUDE_UNTRACKED) {
267 		opts.flags |= GIT_DIFF_INCLUDE_UNTRACKED |
268 			GIT_DIFF_RECURSE_UNTRACKED_DIRS;
269 		data.include_untracked = true;
270 	}
271 
272 	if (flags & GIT_STASH_INCLUDE_IGNORED) {
273 		opts.flags |= GIT_DIFF_INCLUDE_IGNORED |
274 			GIT_DIFF_RECURSE_IGNORED_DIRS;
275 		data.include_ignored = true;
276 	}
277 
278 	if ((error = git_commit_tree(&i_tree, i_commit)) < 0)
279 		goto cleanup;
280 
281 	if ((error = git_diff_tree_to_workdir(&diff, repo, i_tree, &opts)) < 0)
282 		goto cleanup;
283 
284 	if ((error = stash_update_index_from_diff(repo, i_index, diff, &data)) < 0)
285 		goto cleanup;
286 
287 	error = build_tree_from_index(tree_out, repo, i_index);
288 
289 cleanup:
290 	git_diff_free(diff);
291 	git_tree_free(i_tree);
292 	git_index_free(i_index);
293 	return error;
294 }
295 
commit_untracked(git_commit ** u_commit,git_repository * repo,const git_signature * stasher,const char * message,git_commit * i_commit,uint32_t flags)296 static int commit_untracked(
297 	git_commit **u_commit,
298 	git_repository *repo,
299 	const git_signature *stasher,
300 	const char *message,
301 	git_commit *i_commit,
302 	uint32_t flags)
303 {
304 	git_tree *u_tree = NULL;
305 	git_oid u_commit_oid;
306 	git_buf msg = GIT_BUF_INIT;
307 	int error;
308 
309 	if ((error = build_untracked_tree(&u_tree, repo, i_commit, flags)) < 0)
310 		goto cleanup;
311 
312 	if ((error = git_buf_printf(&msg, "untracked files on %s\n", message)) < 0)
313 		goto cleanup;
314 
315 	if ((error = git_commit_create(
316 		&u_commit_oid,
317 		repo,
318 		NULL,
319 		stasher,
320 		stasher,
321 		NULL,
322 		git_buf_cstr(&msg),
323 		u_tree,
324 		0,
325 		NULL)) < 0)
326 		goto cleanup;
327 
328 	error = git_commit_lookup(u_commit, repo, &u_commit_oid);
329 
330 cleanup:
331 	git_tree_free(u_tree);
332 	git_buf_dispose(&msg);
333 	return error;
334 }
335 
stash_delta_merge(const git_diff_delta * a,const git_diff_delta * b,git_pool * pool)336 static git_diff_delta *stash_delta_merge(
337 	const git_diff_delta *a,
338 	const git_diff_delta *b,
339 	git_pool *pool)
340 {
341 	/* Special case for stash: if a file is deleted in the index, but exists
342 	 * in the working tree, we need to stash the workdir copy for the workdir.
343 	 */
344 	if (a->status == GIT_DELTA_DELETED && b->status == GIT_DELTA_UNTRACKED) {
345 		git_diff_delta *dup = git_diff__delta_dup(b, pool);
346 
347 		if (dup)
348 			dup->status = GIT_DELTA_MODIFIED;
349 		return dup;
350 	}
351 
352 	return git_diff__merge_like_cgit(a, b, pool);
353 }
354 
build_workdir_tree(git_tree ** tree_out,git_repository * repo,git_index * i_index,git_commit * b_commit)355 static int build_workdir_tree(
356 	git_tree **tree_out,
357 	git_repository *repo,
358 	git_index *i_index,
359 	git_commit *b_commit)
360 {
361 	git_tree *b_tree = NULL;
362 	git_diff *diff = NULL, *idx_to_wd = NULL;
363 	git_diff_options opts = GIT_DIFF_OPTIONS_INIT;
364 	struct stash_update_rules data = {0};
365 	int error;
366 
367 	opts.flags = GIT_DIFF_IGNORE_SUBMODULES | GIT_DIFF_INCLUDE_UNTRACKED;
368 
369 	if ((error = git_commit_tree(&b_tree, b_commit)) < 0)
370 		goto cleanup;
371 
372 	if ((error = git_diff_tree_to_index(&diff, repo, b_tree, i_index, &opts)) < 0 ||
373 		(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)
375 		goto cleanup;
376 
377 	data.include_changed = true;
378 
379 	if ((error = stash_update_index_from_diff(repo, i_index, diff, &data)) < 0)
380 		goto cleanup;
381 
382 	error = build_tree_from_index(tree_out, repo, i_index);
383 
384 cleanup:
385 	git_diff_free(idx_to_wd);
386 	git_diff_free(diff);
387 	git_tree_free(b_tree);
388 
389 	return error;
390 }
391 
commit_worktree(git_oid * w_commit_oid,git_repository * repo,const git_signature * stasher,const char * message,git_commit * i_commit,git_commit * b_commit,git_commit * u_commit)392 static int commit_worktree(
393 	git_oid *w_commit_oid,
394 	git_repository *repo,
395 	const git_signature *stasher,
396 	const char *message,
397 	git_commit *i_commit,
398 	git_commit *b_commit,
399 	git_commit *u_commit)
400 {
401 	int error = 0;
402 	git_tree *w_tree = NULL, *i_tree = NULL;
403 	git_index *i_index = NULL;
404 	const git_commit *parents[] = {	NULL, NULL,	NULL };
405 	int ignorecase;
406 
407 	parents[0] = b_commit;
408 	parents[1] = i_commit;
409 	parents[2] = u_commit;
410 
411 	if ((error = git_commit_tree(&i_tree, i_commit)) < 0)
412 		goto cleanup;
413 
414 	if ((error = git_index_new(&i_index)) < 0 ||
415 		(error = git_repository__cvar(&ignorecase, repo, GIT_CVAR_IGNORECASE)) < 0)
416 		goto cleanup;
417 
418 	git_index__set_ignore_case(i_index, ignorecase);
419 
420 	if ((error = git_index_read_tree(i_index, i_tree)) < 0)
421 		goto cleanup;
422 
423 	if ((error = build_workdir_tree(&w_tree, repo, i_index, b_commit)) < 0)
424 		goto cleanup;
425 
426 	error = git_commit_create(
427 		w_commit_oid,
428 		repo,
429 		NULL,
430 		stasher,
431 		stasher,
432 		NULL,
433 		message,
434 		w_tree,
435 		u_commit ? 3 : 2,
436 		parents);
437 
438 cleanup:
439 	git_tree_free(i_tree);
440 	git_tree_free(w_tree);
441 	git_index_free(i_index);
442 	return error;
443 }
444 
prepare_worktree_commit_message(git_buf * msg,const char * user_message)445 static int prepare_worktree_commit_message(
446 	git_buf* msg,
447 	const char *user_message)
448 {
449 	git_buf buf = GIT_BUF_INIT;
450 	int error;
451 
452 	if ((error = git_buf_set(&buf, git_buf_cstr(msg), git_buf_len(msg))) < 0)
453 		return error;
454 
455 	git_buf_clear(msg);
456 
457 	if (!user_message)
458 		git_buf_printf(msg, "WIP on %s", git_buf_cstr(&buf));
459 	else {
460 		const char *colon;
461 
462 		if ((colon = strchr(git_buf_cstr(&buf), ':')) == NULL)
463 			goto cleanup;
464 
465 		git_buf_puts(msg, "On ");
466 		git_buf_put(msg, git_buf_cstr(&buf), colon - buf.ptr);
467 		git_buf_printf(msg, ": %s\n", user_message);
468 	}
469 
470 	error = (git_buf_oom(msg) || git_buf_oom(&buf)) ? -1 : 0;
471 
472 cleanup:
473 	git_buf_dispose(&buf);
474 
475 	return error;
476 }
477 
update_reflog(git_oid * w_commit_oid,git_repository * repo,const char * message)478 static int update_reflog(
479 	git_oid *w_commit_oid,
480 	git_repository *repo,
481 	const char *message)
482 {
483 	git_reference *stash;
484 	int error;
485 
486 	if ((error = git_reference_ensure_log(repo, GIT_REFS_STASH_FILE)) < 0)
487 		return error;
488 
489 	error = git_reference_create(&stash, repo, GIT_REFS_STASH_FILE, w_commit_oid, 1, message);
490 
491 	git_reference_free(stash);
492 
493 	return error;
494 }
495 
is_dirty_cb(const char * path,unsigned int status,void * payload)496 static int is_dirty_cb(const char *path, unsigned int status, void *payload)
497 {
498 	GIT_UNUSED(path);
499 	GIT_UNUSED(status);
500 	GIT_UNUSED(payload);
501 
502 	return GIT_PASSTHROUGH;
503 }
504 
ensure_there_are_changes_to_stash(git_repository * repo,bool include_untracked_files,bool include_ignored_files)505 static int ensure_there_are_changes_to_stash(
506 	git_repository *repo,
507 	bool include_untracked_files,
508 	bool include_ignored_files)
509 {
510 	int error;
511 	git_status_options opts = GIT_STATUS_OPTIONS_INIT;
512 
513 	opts.show  = GIT_STATUS_SHOW_INDEX_AND_WORKDIR;
514 	opts.flags = GIT_STATUS_OPT_EXCLUDE_SUBMODULES;
515 
516 	if (include_untracked_files)
517 		opts.flags |= GIT_STATUS_OPT_INCLUDE_UNTRACKED |
518 			GIT_STATUS_OPT_RECURSE_UNTRACKED_DIRS;
519 
520 	if (include_ignored_files)
521 		opts.flags |= GIT_STATUS_OPT_INCLUDE_IGNORED |
522 			GIT_STATUS_OPT_RECURSE_IGNORED_DIRS;
523 
524 	error = git_status_foreach_ext(repo, &opts, is_dirty_cb, NULL);
525 
526 	if (error == GIT_PASSTHROUGH)
527 		return 0;
528 
529 	if (!error)
530 		return create_error(GIT_ENOTFOUND, "there is nothing to stash.");
531 
532 	return error;
533 }
534 
reset_index_and_workdir(git_repository * repo,git_commit * commit,bool remove_untracked,bool remove_ignored)535 static int reset_index_and_workdir(
536 	git_repository *repo,
537 	git_commit *commit,
538 	bool remove_untracked,
539 	bool remove_ignored)
540 {
541 	git_checkout_options opts = GIT_CHECKOUT_OPTIONS_INIT;
542 
543 	opts.checkout_strategy = GIT_CHECKOUT_FORCE;
544 
545 	if (remove_untracked)
546 		opts.checkout_strategy |= GIT_CHECKOUT_REMOVE_UNTRACKED;
547 
548 	if (remove_ignored)
549 		opts.checkout_strategy |= GIT_CHECKOUT_REMOVE_IGNORED;
550 
551 	return git_checkout_tree(repo, (git_object *)commit, &opts);
552 }
553 
git_stash_save(git_oid * out,git_repository * repo,const git_signature * stasher,const char * message,uint32_t flags)554 int git_stash_save(
555 	git_oid *out,
556 	git_repository *repo,
557 	const git_signature *stasher,
558 	const char *message,
559 	uint32_t flags)
560 {
561 	git_index *index = NULL;
562 	git_commit *b_commit = NULL, *i_commit = NULL, *u_commit = NULL;
563 	git_buf msg = GIT_BUF_INIT;
564 	int error;
565 
566 	assert(out && repo && stasher);
567 
568 	if ((error = git_repository__ensure_not_bare(repo, "stash save")) < 0)
569 		return error;
570 
571 	if ((error = retrieve_base_commit_and_message(&b_commit, &msg, repo)) < 0)
572 		goto cleanup;
573 
574 	if ((error = ensure_there_are_changes_to_stash(
575 		repo,
576 		(flags & GIT_STASH_INCLUDE_UNTRACKED) != 0,
577 		(flags & GIT_STASH_INCLUDE_IGNORED) != 0)) < 0)
578 		goto cleanup;
579 
580 	if ((error = git_repository_index(&index, repo)) < 0)
581 		goto cleanup;
582 
583 	if ((error = commit_index(
584 			&i_commit, repo, index, stasher, git_buf_cstr(&msg), b_commit)) < 0)
585 		goto cleanup;
586 
587 	if ((flags & (GIT_STASH_INCLUDE_UNTRACKED | GIT_STASH_INCLUDE_IGNORED)) &&
588 		(error = commit_untracked(
589 			&u_commit, repo, stasher, git_buf_cstr(&msg),
590 			i_commit, flags)) < 0)
591 		goto cleanup;
592 
593 	if ((error = prepare_worktree_commit_message(&msg, message)) < 0)
594 		goto cleanup;
595 
596 	if ((error = commit_worktree(
597 			out, repo, stasher, git_buf_cstr(&msg),
598 			i_commit, b_commit, u_commit)) < 0)
599 		goto cleanup;
600 
601 	git_buf_rtrim(&msg);
602 
603 	if ((error = update_reflog(out, repo, git_buf_cstr(&msg))) < 0)
604 		goto cleanup;
605 
606 	if ((error = reset_index_and_workdir(
607 		repo,
608 		((flags & GIT_STASH_KEEP_INDEX) != 0) ? i_commit : b_commit,
609 		(flags & GIT_STASH_INCLUDE_UNTRACKED) != 0,
610 		(flags & GIT_STASH_INCLUDE_IGNORED) != 0)) < 0)
611 		goto cleanup;
612 
613 cleanup:
614 
615 	git_buf_dispose(&msg);
616 	git_commit_free(i_commit);
617 	git_commit_free(b_commit);
618 	git_commit_free(u_commit);
619 	git_index_free(index);
620 
621 	return error;
622 }
623 
retrieve_stash_commit(git_commit ** commit,git_repository * repo,size_t index)624 static int retrieve_stash_commit(
625 	git_commit **commit,
626 	git_repository *repo,
627 	size_t index)
628 {
629 	git_reference *stash = NULL;
630 	git_reflog *reflog = NULL;
631 	int error;
632 	size_t max;
633 	const git_reflog_entry *entry;
634 
635 	if ((error = git_reference_lookup(&stash, repo, GIT_REFS_STASH_FILE)) < 0)
636 		goto cleanup;
637 
638 	if ((error = git_reflog_read(&reflog, repo, GIT_REFS_STASH_FILE)) < 0)
639 		goto cleanup;
640 
641 	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 		goto cleanup;
646 	}
647 
648 	entry = git_reflog_entry_byindex(reflog, index);
649 	if ((error = git_commit_lookup(commit, repo, git_reflog_entry_id_new(entry))) < 0)
650 		goto cleanup;
651 
652 cleanup:
653 	git_reference_free(stash);
654 	git_reflog_free(reflog);
655 	return error;
656 }
657 
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)658 static int retrieve_stash_trees(
659 	git_tree **out_stash_tree,
660 	git_tree **out_base_tree,
661 	git_tree **out_index_tree,
662 	git_tree **out_index_parent_tree,
663 	git_tree **out_untracked_tree,
664 	git_commit *stash_commit)
665 {
666 	git_tree *stash_tree = NULL;
667 	git_commit *base_commit = NULL;
668 	git_tree *base_tree = NULL;
669 	git_commit *index_commit = NULL;
670 	git_tree *index_tree = NULL;
671 	git_commit *index_parent_commit = NULL;
672 	git_tree *index_parent_tree = NULL;
673 	git_commit *untracked_commit = NULL;
674 	git_tree *untracked_tree = NULL;
675 	int error;
676 
677 	if ((error = git_commit_tree(&stash_tree, stash_commit)) < 0)
678 		goto cleanup;
679 
680 	if ((error = git_commit_parent(&base_commit, stash_commit, 0)) < 0)
681 		goto cleanup;
682 	if ((error = git_commit_tree(&base_tree, base_commit)) < 0)
683 		goto cleanup;
684 
685 	if ((error = git_commit_parent(&index_commit, stash_commit, 1)) < 0)
686 		goto cleanup;
687 	if ((error = git_commit_tree(&index_tree, index_commit)) < 0)
688 		goto cleanup;
689 
690 	if ((error = git_commit_parent(&index_parent_commit, index_commit, 0)) < 0)
691 		goto cleanup;
692 	if ((error = git_commit_tree(&index_parent_tree, index_parent_commit)) < 0)
693 		goto cleanup;
694 
695 	if (git_commit_parentcount(stash_commit) == 3) {
696 		if ((error = git_commit_parent(&untracked_commit, stash_commit, 2)) < 0)
697 			goto cleanup;
698 		if ((error = git_commit_tree(&untracked_tree, untracked_commit)) < 0)
699 			goto cleanup;
700 	}
701 
702 	*out_stash_tree = stash_tree;
703 	*out_base_tree = base_tree;
704 	*out_index_tree = index_tree;
705 	*out_index_parent_tree = index_parent_tree;
706 	*out_untracked_tree = untracked_tree;
707 
708 cleanup:
709 	git_commit_free(untracked_commit);
710 	git_commit_free(index_parent_commit);
711 	git_commit_free(index_commit);
712 	git_commit_free(base_commit);
713 	if (error < 0) {
714 		git_tree_free(stash_tree);
715 		git_tree_free(base_tree);
716 		git_tree_free(index_tree);
717 		git_tree_free(index_parent_tree);
718 		git_tree_free(untracked_tree);
719 	}
720 	return error;
721 }
722 
merge_indexes(git_index ** out,git_repository * repo,git_tree * ancestor_tree,git_index * ours_index,git_index * theirs_index)723 static int merge_indexes(
724 	git_index **out,
725 	git_repository *repo,
726 	git_tree *ancestor_tree,
727 	git_index *ours_index,
728 	git_index *theirs_index)
729 {
730 	git_iterator *ancestor = NULL, *ours = NULL, *theirs = NULL;
731 	git_iterator_options iter_opts = GIT_ITERATOR_OPTIONS_INIT;
732 	int error;
733 
734 	iter_opts.flags = GIT_ITERATOR_DONT_IGNORE_CASE;
735 
736 	if ((error = git_iterator_for_tree(&ancestor, ancestor_tree, &iter_opts)) < 0 ||
737 		(error = git_iterator_for_index(&ours, repo, ours_index, &iter_opts)) < 0 ||
738 		(error = git_iterator_for_index(&theirs, repo, theirs_index, &iter_opts)) < 0)
739 		goto done;
740 
741 	error = git_merge__iterators(out, repo, ancestor, ours, theirs, NULL);
742 
743 done:
744 	git_iterator_free(ancestor);
745 	git_iterator_free(ours);
746 	git_iterator_free(theirs);
747 	return error;
748 }
749 
merge_index_and_tree(git_index ** out,git_repository * repo,git_tree * ancestor_tree,git_index * ours_index,git_tree * theirs_tree)750 static int merge_index_and_tree(
751 	git_index **out,
752 	git_repository *repo,
753 	git_tree *ancestor_tree,
754 	git_index *ours_index,
755 	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 	int error;
760 
761 	iter_opts.flags = GIT_ITERATOR_DONT_IGNORE_CASE;
762 
763 	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 done:
771 	git_iterator_free(ancestor);
772 	git_iterator_free(ours);
773 	git_iterator_free(theirs);
774 	return error;
775 }
776 
normalize_apply_options(git_stash_apply_options * opts,const git_stash_apply_options * given_apply_opts)777 static void normalize_apply_options(
778 	git_stash_apply_options *opts,
779 	const git_stash_apply_options *given_apply_opts)
780 {
781 	if (given_apply_opts != NULL) {
782 		memcpy(opts, given_apply_opts, sizeof(git_stash_apply_options));
783 	} else {
784 		git_stash_apply_options default_apply_opts = GIT_STASH_APPLY_OPTIONS_INIT;
785 		memcpy(opts, &default_apply_opts, sizeof(git_stash_apply_options));
786 	}
787 
788 	opts->checkout_options.checkout_strategy |= GIT_CHECKOUT_NO_REFRESH;
789 
790 	if (!opts->checkout_options.our_label)
791 		opts->checkout_options.our_label = "Updated upstream";
792 
793 	if (!opts->checkout_options.their_label)
794 		opts->checkout_options.their_label = "Stashed changes";
795 }
796 
git_stash_apply_init_options(git_stash_apply_options * opts,unsigned int version)797 int git_stash_apply_init_options(git_stash_apply_options *opts, unsigned int version)
798 {
799 	GIT_INIT_STRUCTURE_FROM_TEMPLATE(
800 		opts, version, git_stash_apply_options, GIT_STASH_APPLY_OPTIONS_INIT);
801 	return 0;
802 }
803 
804 #define NOTIFY_PROGRESS(opts, progress_type)				\
805 	do {								\
806 		if ((opts).progress_cb &&				\
807 		    (error = (opts).progress_cb((progress_type), (opts).progress_payload))) { \
808 			error = (error < 0) ? error : -1;		\
809 			goto cleanup;					\
810 		}							\
811 	} while(false);
812 
ensure_clean_index(git_repository * repo,git_index * index)813 static int ensure_clean_index(git_repository *repo, git_index *index)
814 {
815 	git_tree *head_tree = NULL;
816 	git_diff *index_diff = NULL;
817 	int error = 0;
818 
819 	if ((error = git_repository_head_tree(&head_tree, repo)) < 0 ||
820 		(error = git_diff_tree_to_index(
821 			&index_diff, repo, head_tree, index, NULL)) < 0)
822 		goto done;
823 
824 	if (git_diff_num_deltas(index_diff) > 0) {
825 		git_error_set(GIT_ERROR_STASH, "%" PRIuZ " uncommitted changes exist in the index",
826 			git_diff_num_deltas(index_diff));
827 		error = GIT_EUNCOMMITTED;
828 	}
829 
830 done:
831 	git_diff_free(index_diff);
832 	git_tree_free(head_tree);
833 	return error;
834 }
835 
stage_new_file(const git_index_entry ** entries,void * data)836 static int stage_new_file(const git_index_entry **entries, void *data)
837 {
838 	git_index *index = data;
839 
840 	if(entries[0] == NULL)
841 		return git_index_add(index, entries[1]);
842 	else
843 		return git_index_add(index, entries[0]);
844 }
845 
stage_new_files(git_index ** out,git_tree * parent_tree,git_tree * tree)846 static int stage_new_files(
847 	git_index **out,
848 	git_tree *parent_tree,
849 	git_tree *tree)
850 {
851 	git_iterator *iterators[2] = { NULL, NULL };
852 	git_iterator_options iterator_options = GIT_ITERATOR_OPTIONS_INIT;
853 	git_index *index = NULL;
854 	int error;
855 
856 	if ((error = git_index_new(&index)) < 0 ||
857 		(error = git_iterator_for_tree(
858 			&iterators[0], parent_tree, &iterator_options)) < 0 ||
859 		(error = git_iterator_for_tree(
860 			&iterators[1], tree, &iterator_options)) < 0)
861 		goto done;
862 
863 	error = git_iterator_walk(iterators, 2, stage_new_file, index);
864 
865 done:
866 	if (error < 0)
867 		git_index_free(index);
868 	else
869 		*out = index;
870 
871 	git_iterator_free(iterators[0]);
872 	git_iterator_free(iterators[1]);
873 
874 	return error;
875 }
876 
git_stash_apply(git_repository * repo,size_t index,const git_stash_apply_options * given_opts)877 int git_stash_apply(
878 	git_repository *repo,
879 	size_t index,
880 	const git_stash_apply_options *given_opts)
881 {
882 	git_stash_apply_options opts;
883 	unsigned int checkout_strategy;
884 	git_commit *stash_commit = NULL;
885 	git_tree *stash_tree = NULL;
886 	git_tree *stash_parent_tree = NULL;
887 	git_tree *index_tree = NULL;
888 	git_tree *index_parent_tree = NULL;
889 	git_tree *untracked_tree = NULL;
890 	git_index *stash_adds = NULL;
891 	git_index *repo_index = NULL;
892 	git_index *unstashed_index = NULL;
893 	git_index *modified_index = NULL;
894 	git_index *untracked_index = NULL;
895 	int error;
896 
897 	GIT_ERROR_CHECK_VERSION(given_opts, GIT_STASH_APPLY_OPTIONS_VERSION, "git_stash_apply_options");
898 
899 	normalize_apply_options(&opts, given_opts);
900 	checkout_strategy = opts.checkout_options.checkout_strategy;
901 
902 	NOTIFY_PROGRESS(opts, GIT_STASH_APPLY_PROGRESS_LOADING_STASH);
903 
904 	/* Retrieve commit corresponding to the given stash */
905 	if ((error = retrieve_stash_commit(&stash_commit, repo, index)) < 0)
906 		goto cleanup;
907 
908 	/* Retrieve all trees in the stash */
909 	if ((error = retrieve_stash_trees(
910 			&stash_tree, &stash_parent_tree, &index_tree,
911 			&index_parent_tree, &untracked_tree, stash_commit)) < 0)
912 		goto cleanup;
913 
914 	/* Load repo index */
915 	if ((error = git_repository_index(&repo_index, repo)) < 0)
916 		goto cleanup;
917 
918 	NOTIFY_PROGRESS(opts, GIT_STASH_APPLY_PROGRESS_ANALYZE_INDEX);
919 
920 	if ((error = ensure_clean_index(repo, repo_index)) < 0)
921 		goto cleanup;
922 
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 		if ((error = merge_index_and_tree(
928 				&unstashed_index, repo, index_parent_tree, repo_index, index_tree)) < 0)
929 			goto cleanup;
930 
931 		if (git_index_has_conflicts(unstashed_index)) {
932 			error = GIT_ECONFLICT;
933 			goto cleanup;
934 		}
935 
936 	/* Otherwise, stage any new files in the stash tree.  (Note: their
937 	 * previously unstaged contents are staged, not the previously staged.)
938 	 */
939 	} else if ((opts.flags & GIT_STASH_APPLY_REINSTATE_INDEX) == 0) {
940 		if ((error = stage_new_files(
941 				&stash_adds, stash_parent_tree, stash_tree)) < 0 ||
942 			(error = merge_indexes(
943 				&unstashed_index, repo, stash_parent_tree, repo_index, stash_adds)) < 0)
944 			goto cleanup;
945 	}
946 
947 	NOTIFY_PROGRESS(opts, GIT_STASH_APPLY_PROGRESS_ANALYZE_MODIFIED);
948 
949 	/* Restore modified files in workdir */
950 	if ((error = merge_index_and_tree(
951 			&modified_index, repo, stash_parent_tree, repo_index, stash_tree)) < 0)
952 		goto cleanup;
953 
954 	/* If applicable, restore untracked / ignored files in workdir */
955 	if (untracked_tree) {
956 		NOTIFY_PROGRESS(opts, GIT_STASH_APPLY_PROGRESS_ANALYZE_UNTRACKED);
957 
958 		if ((error = merge_index_and_tree(&untracked_index, repo, NULL, repo_index, untracked_tree)) < 0)
959 			goto cleanup;
960 	}
961 
962 	if (untracked_index) {
963 		opts.checkout_options.checkout_strategy |= GIT_CHECKOUT_DONT_UPDATE_INDEX;
964 
965 		NOTIFY_PROGRESS(opts, GIT_STASH_APPLY_PROGRESS_CHECKOUT_UNTRACKED);
966 
967 		if ((error = git_checkout_index(repo, untracked_index, &opts.checkout_options)) < 0)
968 			goto cleanup;
969 
970 		opts.checkout_options.checkout_strategy = checkout_strategy;
971 	}
972 
973 
974 	/* If there are conflicts in the modified index, then we need to actually
975 	 * check that out as the repo's index.  Otherwise, we don't update the
976 	 * index.
977 	 */
978 
979 	if (!git_index_has_conflicts(modified_index))
980 		opts.checkout_options.checkout_strategy |= GIT_CHECKOUT_DONT_UPDATE_INDEX;
981 
982 	/* Check out the modified index using the existing repo index as baseline,
983 	 * so that existing modifications in the index can be rewritten even when
984 	 * checking out safely.
985 	 */
986 	opts.checkout_options.baseline_index = repo_index;
987 
988 	NOTIFY_PROGRESS(opts, GIT_STASH_APPLY_PROGRESS_CHECKOUT_MODIFIED);
989 
990 	if ((error = git_checkout_index(repo, modified_index, &opts.checkout_options)) < 0)
991 		goto cleanup;
992 
993 	if (unstashed_index && !git_index_has_conflicts(modified_index)) {
994 		if ((error = git_index_read_index(repo_index, unstashed_index)) < 0)
995 			goto cleanup;
996 	}
997 
998 	NOTIFY_PROGRESS(opts, GIT_STASH_APPLY_PROGRESS_DONE);
999 
1000 	error = git_index_write(repo_index);
1001 
1002 cleanup:
1003 	git_index_free(untracked_index);
1004 	git_index_free(modified_index);
1005 	git_index_free(unstashed_index);
1006 	git_index_free(stash_adds);
1007 	git_index_free(repo_index);
1008 	git_tree_free(untracked_tree);
1009 	git_tree_free(index_parent_tree);
1010 	git_tree_free(index_tree);
1011 	git_tree_free(stash_parent_tree);
1012 	git_tree_free(stash_tree);
1013 	git_commit_free(stash_commit);
1014 	return error;
1015 }
1016 
git_stash_foreach(git_repository * repo,git_stash_cb callback,void * payload)1017 int git_stash_foreach(
1018 	git_repository *repo,
1019 	git_stash_cb callback,
1020 	void *payload)
1021 {
1022 	git_reference *stash;
1023 	git_reflog *reflog = NULL;
1024 	int error;
1025 	size_t i, max;
1026 	const git_reflog_entry *entry;
1027 
1028 	error = git_reference_lookup(&stash, repo, GIT_REFS_STASH_FILE);
1029 	if (error == GIT_ENOTFOUND) {
1030 		git_error_clear();
1031 		return 0;
1032 	}
1033 	if (error < 0)
1034 		goto cleanup;
1035 
1036 	if ((error = git_reflog_read(&reflog, repo, GIT_REFS_STASH_FILE)) < 0)
1037 		goto cleanup;
1038 
1039 	max = git_reflog_entrycount(reflog);
1040 	for (i = 0; i < max; i++) {
1041 		entry = git_reflog_entry_byindex(reflog, i);
1042 
1043 		error = callback(i,
1044 			git_reflog_entry_message(entry),
1045 			git_reflog_entry_id_new(entry),
1046 			payload);
1047 
1048 		if (error) {
1049 			git_error_set_after_callback(error);
1050 			break;
1051 		}
1052 	}
1053 
1054 cleanup:
1055 	git_reference_free(stash);
1056 	git_reflog_free(reflog);
1057 	return error;
1058 }
1059 
git_stash_drop(git_repository * repo,size_t index)1060 int git_stash_drop(
1061 	git_repository *repo,
1062 	size_t index)
1063 {
1064 	git_transaction *tx;
1065 	git_reference *stash = NULL;
1066 	git_reflog *reflog = NULL;
1067 	size_t max;
1068 	int error;
1069 
1070 	if ((error = git_transaction_new(&tx, repo)) < 0)
1071 		return error;
1072 
1073 	if ((error = git_transaction_lock_ref(tx, GIT_REFS_STASH_FILE)) < 0)
1074 		goto cleanup;
1075 
1076 	if ((error = git_reference_lookup(&stash, repo, GIT_REFS_STASH_FILE)) < 0)
1077 		goto cleanup;
1078 
1079 	if ((error = git_reflog_read(&reflog, repo, GIT_REFS_STASH_FILE)) < 0)
1080 		goto cleanup;
1081 
1082 	max = git_reflog_entrycount(reflog);
1083 
1084 	if (!max || index > max - 1) {
1085 		error = GIT_ENOTFOUND;
1086 		git_error_set(GIT_ERROR_STASH, "no stashed state at position %" PRIuZ, index);
1087 		goto cleanup;
1088 	}
1089 
1090 	if ((error = git_reflog_drop(reflog, index, true)) < 0)
1091 		goto cleanup;
1092 
1093 	if ((error = git_transaction_set_reflog(tx, GIT_REFS_STASH_FILE, reflog)) < 0)
1094 		goto cleanup;
1095 
1096 	if (max == 1) {
1097 		if ((error = git_transaction_remove(tx, GIT_REFS_STASH_FILE)) < 0)
1098 			goto cleanup;
1099 	} else if (index == 0) {
1100 		const git_reflog_entry *entry;
1101 
1102 		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;
1105 	}
1106 
1107 	error = git_transaction_commit(tx);
1108 
1109 cleanup:
1110 	git_reference_free(stash);
1111 	git_transaction_free(tx);
1112 	git_reflog_free(reflog);
1113 	return error;
1114 }
1115 
git_stash_pop(git_repository * repo,size_t index,const git_stash_apply_options * options)1116 int git_stash_pop(
1117 	git_repository *repo,
1118 	size_t index,
1119 	const git_stash_apply_options *options)
1120 {
1121 	int error;
1122 
1123 	if ((error = git_stash_apply(repo, index, options)) < 0)
1124 		return error;
1125 
1126 	return git_stash_drop(repo, index);
1127 }
1128