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 "checkout.h"
9 
10 #include "git2/repository.h"
11 #include "git2/refs.h"
12 #include "git2/tree.h"
13 #include "git2/blob.h"
14 #include "git2/config.h"
15 #include "git2/diff.h"
16 #include "git2/submodule.h"
17 #include "git2/sys/index.h"
18 #include "git2/sys/filter.h"
19 #include "git2/merge.h"
20 
21 #include "refs.h"
22 #include "repository.h"
23 #include "index.h"
24 #include "filter.h"
25 #include "blob.h"
26 #include "diff.h"
27 #include "diff_generate.h"
28 #include "pathspec.h"
29 #include "diff_xdiff.h"
30 #include "path.h"
31 #include "attr.h"
32 #include "pool.h"
33 #include "strmap.h"
34 
35 /* See docs/checkout-internals.md for more information */
36 
37 enum {
38 	CHECKOUT_ACTION__NONE = 0,
39 	CHECKOUT_ACTION__REMOVE = 1,
40 	CHECKOUT_ACTION__UPDATE_BLOB = 2,
41 	CHECKOUT_ACTION__UPDATE_SUBMODULE = 4,
42 	CHECKOUT_ACTION__CONFLICT = 8,
43 	CHECKOUT_ACTION__REMOVE_CONFLICT = 16,
44 	CHECKOUT_ACTION__UPDATE_CONFLICT = 32,
45 	CHECKOUT_ACTION__MAX = 32,
46 	CHECKOUT_ACTION__REMOVE_AND_UPDATE =
47 		(CHECKOUT_ACTION__UPDATE_BLOB | CHECKOUT_ACTION__REMOVE),
48 };
49 
50 typedef struct {
51 	git_repository *repo;
52 	git_iterator *target;
53 	git_diff *diff;
54 	git_checkout_options opts;
55 	bool opts_free_baseline;
56 	char *pfx;
57 	git_index *index;
58 	git_pool pool;
59 	git_vector removes;
60 	git_vector remove_conflicts;
61 	git_vector update_conflicts;
62 	git_vector *update_reuc;
63 	git_vector *update_names;
64 	git_buf target_path;
65 	size_t target_len;
66 	git_buf tmp;
67 	unsigned int strategy;
68 	int can_symlink;
69 	int respect_filemode;
70 	bool reload_submodules;
71 	size_t total_steps;
72 	size_t completed_steps;
73 	git_checkout_perfdata perfdata;
74 	git_strmap *mkdir_map;
75 	git_attr_session attr_session;
76 } checkout_data;
77 
78 typedef struct {
79 	const git_index_entry *ancestor;
80 	const git_index_entry *ours;
81 	const git_index_entry *theirs;
82 
83 	int name_collision:1,
84 		directoryfile:1,
85 		one_to_two:1,
86 		binary:1,
87 		submodule:1;
88 } checkout_conflictdata;
89 
checkout_notify(checkout_data * data,git_checkout_notify_t why,const git_diff_delta * delta,const git_index_entry * wditem)90 static int checkout_notify(
91 	checkout_data *data,
92 	git_checkout_notify_t why,
93 	const git_diff_delta *delta,
94 	const git_index_entry *wditem)
95 {
96 	git_diff_file wdfile;
97 	const git_diff_file *baseline = NULL, *target = NULL, *workdir = NULL;
98 	const char *path = NULL;
99 
100 	if (!data->opts.notify_cb ||
101 		(why & data->opts.notify_flags) == 0)
102 		return 0;
103 
104 	if (wditem) {
105 		memset(&wdfile, 0, sizeof(wdfile));
106 
107 		git_oid_cpy(&wdfile.id, &wditem->id);
108 		wdfile.path = wditem->path;
109 		wdfile.size = wditem->file_size;
110 		wdfile.flags = GIT_DIFF_FLAG_VALID_ID;
111 		wdfile.mode = wditem->mode;
112 
113 		workdir = &wdfile;
114 
115 		path = wditem->path;
116 	}
117 
118 	if (delta) {
119 		switch (delta->status) {
120 		case GIT_DELTA_UNMODIFIED:
121 		case GIT_DELTA_MODIFIED:
122 		case GIT_DELTA_TYPECHANGE:
123 		default:
124 			baseline = &delta->old_file;
125 			target = &delta->new_file;
126 			break;
127 		case GIT_DELTA_ADDED:
128 		case GIT_DELTA_IGNORED:
129 		case GIT_DELTA_UNTRACKED:
130 		case GIT_DELTA_UNREADABLE:
131 			target = &delta->new_file;
132 			break;
133 		case GIT_DELTA_DELETED:
134 			baseline = &delta->old_file;
135 			break;
136 		}
137 
138 		path = delta->old_file.path;
139 	}
140 
141 	{
142 		int error = data->opts.notify_cb(
143 			why, path, baseline, target, workdir, data->opts.notify_payload);
144 
145 		return git_error_set_after_callback_function(
146 			error, "git_checkout notification");
147 	}
148 }
149 
is_workdir_base_or_new(const git_oid * workdir_id,const git_diff_file * baseitem,const git_diff_file * newitem)150 GIT_INLINE(bool) is_workdir_base_or_new(
151 	const git_oid *workdir_id,
152 	const git_diff_file *baseitem,
153 	const git_diff_file *newitem)
154 {
155 	return (git_oid__cmp(&baseitem->id, workdir_id) == 0 ||
156 		git_oid__cmp(&newitem->id, workdir_id) == 0);
157 }
158 
is_filemode_changed(git_filemode_t a,git_filemode_t b,int respect_filemode)159 GIT_INLINE(bool) is_filemode_changed(git_filemode_t a, git_filemode_t b, int respect_filemode)
160 {
161 	/* If core.filemode = false, ignore links in the repository and executable bit changes */
162 	if (!respect_filemode) {
163 		if (a == S_IFLNK)
164 			a = GIT_FILEMODE_BLOB;
165 		if (b == S_IFLNK)
166 			b = GIT_FILEMODE_BLOB;
167 
168 		a &= ~0111;
169 		b &= ~0111;
170 	}
171 
172 	return (a != b);
173 }
174 
checkout_is_workdir_modified(checkout_data * data,const git_diff_file * baseitem,const git_diff_file * newitem,const git_index_entry * wditem)175 static bool checkout_is_workdir_modified(
176 	checkout_data *data,
177 	const git_diff_file *baseitem,
178 	const git_diff_file *newitem,
179 	const git_index_entry *wditem)
180 {
181 	git_oid oid;
182 	const git_index_entry *ie;
183 
184 	/* handle "modified" submodule */
185 	if (wditem->mode == GIT_FILEMODE_COMMIT) {
186 		git_submodule *sm;
187 		unsigned int sm_status = 0;
188 		const git_oid *sm_oid = NULL;
189 		bool rval = false;
190 
191 		if (git_submodule_lookup(&sm, data->repo, wditem->path) < 0) {
192 			git_error_clear();
193 			return true;
194 		}
195 
196 		if (git_submodule_status(&sm_status, data->repo, wditem->path, GIT_SUBMODULE_IGNORE_UNSPECIFIED) < 0 ||
197 		    GIT_SUBMODULE_STATUS_IS_WD_DIRTY(sm_status))
198 			rval = true;
199 		else if ((sm_oid = git_submodule_wd_id(sm)) == NULL)
200 			rval = false;
201 		else
202 			rval = (git_oid__cmp(&baseitem->id, sm_oid) != 0);
203 
204 		git_submodule_free(sm);
205 		return rval;
206 	}
207 
208 	/*
209 	 * Look at the cache to decide if the workdir is modified: if the
210 	 * cache contents match the workdir contents, then we do not need
211 	 * to examine the working directory directly, instead we can
212 	 * examine the cache to see if _it_ has been modified.  This allows
213 	 * us to avoid touching the disk.
214 	 */
215 	ie = git_index_get_bypath(data->index, wditem->path, 0);
216 
217 	if (ie != NULL &&
218 	    !git_index_entry_newer_than_index(ie, data->index) &&
219 	    git_index_time_eq(&wditem->mtime, &ie->mtime) &&
220 	    wditem->file_size == ie->file_size &&
221 	    !is_filemode_changed(wditem->mode, ie->mode, data->respect_filemode)) {
222 
223 		/* The workdir is modified iff the index entry is modified */
224 		return !is_workdir_base_or_new(&ie->id, baseitem, newitem) ||
225 			is_filemode_changed(baseitem->mode, ie->mode, data->respect_filemode);
226 	}
227 
228 	/* depending on where base is coming from, we may or may not know
229 	 * the actual size of the data, so we can't rely on this shortcut.
230 	 */
231 	if (baseitem->size && wditem->file_size != baseitem->size)
232 		return true;
233 
234 	/* if the workdir item is a directory, it cannot be a modified file */
235 	if (S_ISDIR(wditem->mode))
236 		return false;
237 
238 	if (is_filemode_changed(baseitem->mode, wditem->mode, data->respect_filemode))
239 		return true;
240 
241 	if (git_diff__oid_for_entry(&oid, data->diff, wditem, wditem->mode, NULL) < 0)
242 		return false;
243 
244 	/* Allow the checkout if the workdir is not modified *or* if the checkout
245 	 * target's contents are already in the working directory.
246 	 */
247 	return !is_workdir_base_or_new(&oid, baseitem, newitem);
248 }
249 
250 #define CHECKOUT_ACTION_IF(FLAG,YES,NO) \
251 	((data->strategy & GIT_CHECKOUT_##FLAG) ? CHECKOUT_ACTION__##YES : CHECKOUT_ACTION__##NO)
252 
checkout_action_common(int * action,checkout_data * data,const git_diff_delta * delta,const git_index_entry * wd)253 static int checkout_action_common(
254 	int *action,
255 	checkout_data *data,
256 	const git_diff_delta *delta,
257 	const git_index_entry *wd)
258 {
259 	git_checkout_notify_t notify = GIT_CHECKOUT_NOTIFY_NONE;
260 
261 	if ((data->strategy & GIT_CHECKOUT_UPDATE_ONLY) != 0)
262 		*action = (*action & ~CHECKOUT_ACTION__REMOVE);
263 
264 	if ((*action & CHECKOUT_ACTION__UPDATE_BLOB) != 0) {
265 		if (S_ISGITLINK(delta->new_file.mode))
266 			*action = (*action & ~CHECKOUT_ACTION__UPDATE_BLOB) |
267 				CHECKOUT_ACTION__UPDATE_SUBMODULE;
268 
269 		/* to "update" a symlink, we must remove the old one first */
270 		if (delta->new_file.mode == GIT_FILEMODE_LINK && wd != NULL)
271 			*action |= CHECKOUT_ACTION__REMOVE;
272 
273 		/* if the file is on disk and doesn't match our mode, force update */
274 		if (wd &&
275 		    GIT_PERMS_IS_EXEC(wd->mode) != GIT_PERMS_IS_EXEC(delta->new_file.mode))
276 			*action |= CHECKOUT_ACTION__REMOVE;
277 
278 		notify = GIT_CHECKOUT_NOTIFY_UPDATED;
279 	}
280 
281 	if ((*action & CHECKOUT_ACTION__CONFLICT) != 0)
282 		notify = GIT_CHECKOUT_NOTIFY_CONFLICT;
283 
284 	return checkout_notify(data, notify, delta, wd);
285 }
286 
checkout_action_no_wd(int * action,checkout_data * data,const git_diff_delta * delta)287 static int checkout_action_no_wd(
288 	int *action,
289 	checkout_data *data,
290 	const git_diff_delta *delta)
291 {
292 	int error = 0;
293 
294 	*action = CHECKOUT_ACTION__NONE;
295 
296 	switch (delta->status) {
297 	case GIT_DELTA_UNMODIFIED: /* case 12 */
298 		error = checkout_notify(data, GIT_CHECKOUT_NOTIFY_DIRTY, delta, NULL);
299 		if (error)
300 			return error;
301 		*action = CHECKOUT_ACTION_IF(RECREATE_MISSING, UPDATE_BLOB, NONE);
302 		break;
303 	case GIT_DELTA_ADDED:    /* case 2 or 28 (and 5 but not really) */
304 		*action = CHECKOUT_ACTION_IF(SAFE, UPDATE_BLOB, NONE);
305 		break;
306 	case GIT_DELTA_MODIFIED: /* case 13 (and 35 but not really) */
307 		*action = CHECKOUT_ACTION_IF(RECREATE_MISSING, UPDATE_BLOB, CONFLICT);
308 		break;
309 	case GIT_DELTA_TYPECHANGE: /* case 21 (B->T) and 28 (T->B)*/
310 		if (delta->new_file.mode == GIT_FILEMODE_TREE)
311 			*action = CHECKOUT_ACTION_IF(SAFE, UPDATE_BLOB, NONE);
312 		break;
313 	case GIT_DELTA_DELETED: /* case 8 or 25 */
314 		*action = CHECKOUT_ACTION_IF(SAFE, REMOVE, NONE);
315 		break;
316 	default: /* impossible */
317 		break;
318 	}
319 
320 	return checkout_action_common(action, data, delta, NULL);
321 }
322 
checkout_target_fullpath(git_buf ** out,checkout_data * data,const char * path)323 static int checkout_target_fullpath(
324 	git_buf **out, checkout_data *data, const char *path)
325 {
326 	git_buf_truncate(&data->target_path, data->target_len);
327 
328 	if (path && git_buf_puts(&data->target_path, path) < 0)
329 		return -1;
330 
331 	if (git_path_validate_workdir_buf(data->repo, &data->target_path) < 0)
332 		return -1;
333 
334 	*out = &data->target_path;
335 
336 	return 0;
337 }
338 
wd_item_is_removable(checkout_data * data,const git_index_entry * wd)339 static bool wd_item_is_removable(
340 	checkout_data *data, const git_index_entry *wd)
341 {
342 	git_buf *full;
343 
344 	if (wd->mode != GIT_FILEMODE_TREE)
345 		return true;
346 
347 	if (checkout_target_fullpath(&full, data, wd->path) < 0)
348 		return false;
349 
350 	return !full || !git_path_contains(full, DOT_GIT);
351 }
352 
checkout_queue_remove(checkout_data * data,const char * path)353 static int checkout_queue_remove(checkout_data *data, const char *path)
354 {
355 	char *copy = git_pool_strdup(&data->pool, path);
356 	GIT_ERROR_CHECK_ALLOC(copy);
357 	return git_vector_insert(&data->removes, copy);
358 }
359 
360 /* note that this advances the iterator over the wd item */
checkout_action_wd_only(checkout_data * data,git_iterator * workdir,const git_index_entry ** wditem,git_vector * pathspec)361 static int checkout_action_wd_only(
362 	checkout_data *data,
363 	git_iterator *workdir,
364 	const git_index_entry **wditem,
365 	git_vector *pathspec)
366 {
367 	int error = 0;
368 	bool remove = false;
369 	git_checkout_notify_t notify = GIT_CHECKOUT_NOTIFY_NONE;
370 	const git_index_entry *wd = *wditem;
371 
372 	if (!git_pathspec__match(
373 			pathspec, wd->path,
374 			(data->strategy & GIT_CHECKOUT_DISABLE_PATHSPEC_MATCH) != 0,
375 			git_iterator_ignore_case(workdir), NULL, NULL)) {
376 
377 		if (wd->mode == GIT_FILEMODE_TREE)
378 			return git_iterator_advance_into(wditem, workdir);
379 		else
380 			return git_iterator_advance(wditem, workdir);
381 	}
382 
383 	/* check if item is tracked in the index but not in the checkout diff */
384 	if (data->index != NULL) {
385 		size_t pos;
386 
387 		error = git_index__find_pos(
388 			&pos, data->index, wd->path, 0, GIT_INDEX_STAGE_ANY);
389 
390 		if (wd->mode != GIT_FILEMODE_TREE) {
391 			if (!error) { /* found by git_index__find_pos call */
392 				notify = GIT_CHECKOUT_NOTIFY_DIRTY;
393 				remove = ((data->strategy & GIT_CHECKOUT_FORCE) != 0);
394 			} else if (error != GIT_ENOTFOUND)
395 				return error;
396 			else
397 				error = 0; /* git_index__find_pos does not set error msg */
398 		} else {
399 			/* for tree entries, we have to see if there are any index
400 			 * entries that are contained inside that tree
401 			 */
402 			const git_index_entry *e = git_index_get_byindex(data->index, pos);
403 
404 			if (e != NULL && data->diff->pfxcomp(e->path, wd->path) == 0)
405 				return git_iterator_advance_into(wditem, workdir);
406 		}
407 	}
408 
409 	if (notify != GIT_CHECKOUT_NOTIFY_NONE) {
410 		/* if we found something in the index, notify and advance */
411 		if ((error = checkout_notify(data, notify, NULL, wd)) != 0)
412 			return error;
413 
414 		if (remove && wd_item_is_removable(data, wd))
415 			error = checkout_queue_remove(data, wd->path);
416 
417 		if (!error)
418 			error = git_iterator_advance(wditem, workdir);
419 	} else {
420 		/* untracked or ignored - can't know which until we advance through */
421 		bool over = false, removable = wd_item_is_removable(data, wd);
422 		git_iterator_status_t untracked_state;
423 
424 		/* copy the entry for issuing notification callback later */
425 		git_index_entry saved_wd = *wd;
426 		git_buf_sets(&data->tmp, wd->path);
427 		saved_wd.path = data->tmp.ptr;
428 
429 		error = git_iterator_advance_over(
430 			wditem, &untracked_state, workdir);
431 		if (error == GIT_ITEROVER)
432 			over = true;
433 		else if (error < 0)
434 			return error;
435 
436 		if (untracked_state == GIT_ITERATOR_STATUS_IGNORED) {
437 			notify = GIT_CHECKOUT_NOTIFY_IGNORED;
438 			remove = ((data->strategy & GIT_CHECKOUT_REMOVE_IGNORED) != 0);
439 		} else {
440 			notify = GIT_CHECKOUT_NOTIFY_UNTRACKED;
441 			remove = ((data->strategy & GIT_CHECKOUT_REMOVE_UNTRACKED) != 0);
442 		}
443 
444 		if ((error = checkout_notify(data, notify, NULL, &saved_wd)) != 0)
445 			return error;
446 
447 		if (remove && removable)
448 			error = checkout_queue_remove(data, saved_wd.path);
449 
450 		if (!error && over) /* restore ITEROVER if needed */
451 			error = GIT_ITEROVER;
452 	}
453 
454 	return error;
455 }
456 
submodule_is_config_only(checkout_data * data,const char * path)457 static bool submodule_is_config_only(
458 	checkout_data *data,
459 	const char *path)
460 {
461 	git_submodule *sm = NULL;
462 	unsigned int sm_loc = 0;
463 	bool rval = false;
464 
465 	if (git_submodule_lookup(&sm, data->repo, path) < 0)
466 		return true;
467 
468 	if (git_submodule_location(&sm_loc, sm) < 0 ||
469 		sm_loc == GIT_SUBMODULE_STATUS_IN_CONFIG)
470 		rval = true;
471 
472 	git_submodule_free(sm);
473 
474 	return rval;
475 }
476 
checkout_is_empty_dir(checkout_data * data,const char * path)477 static bool checkout_is_empty_dir(checkout_data *data, const char *path)
478 {
479 	git_buf *fullpath;
480 
481 	if (checkout_target_fullpath(&fullpath, data, path) < 0)
482 		return false;
483 
484 	return git_path_is_empty_dir(fullpath->ptr);
485 }
486 
checkout_action_with_wd(int * action,checkout_data * data,const git_diff_delta * delta,git_iterator * workdir,const git_index_entry * wd)487 static int checkout_action_with_wd(
488 	int *action,
489 	checkout_data *data,
490 	const git_diff_delta *delta,
491 	git_iterator *workdir,
492 	const git_index_entry *wd)
493 {
494 	*action = CHECKOUT_ACTION__NONE;
495 
496 	switch (delta->status) {
497 	case GIT_DELTA_UNMODIFIED: /* case 14/15 or 33 */
498 		if (checkout_is_workdir_modified(data, &delta->old_file, &delta->new_file, wd)) {
499 			GIT_ERROR_CHECK_ERROR(
500 				checkout_notify(data, GIT_CHECKOUT_NOTIFY_DIRTY, delta, wd) );
501 			*action = CHECKOUT_ACTION_IF(FORCE, UPDATE_BLOB, NONE);
502 		}
503 		break;
504 	case GIT_DELTA_ADDED: /* case 3, 4 or 6 */
505 		if (git_iterator_current_is_ignored(workdir))
506 			*action = CHECKOUT_ACTION_IF(DONT_OVERWRITE_IGNORED, CONFLICT, UPDATE_BLOB);
507 		else
508 			*action = CHECKOUT_ACTION_IF(FORCE, UPDATE_BLOB, CONFLICT);
509 		break;
510 	case GIT_DELTA_DELETED: /* case 9 or 10 (or 26 but not really) */
511 		if (checkout_is_workdir_modified(data, &delta->old_file, &delta->new_file, wd))
512 			*action = CHECKOUT_ACTION_IF(FORCE, REMOVE, CONFLICT);
513 		else
514 			*action = CHECKOUT_ACTION_IF(SAFE, REMOVE, NONE);
515 		break;
516 	case GIT_DELTA_MODIFIED: /* case 16, 17, 18 (or 36 but not really) */
517 		if (wd->mode != GIT_FILEMODE_COMMIT &&
518 			checkout_is_workdir_modified(data, &delta->old_file, &delta->new_file, wd))
519 			*action = CHECKOUT_ACTION_IF(FORCE, UPDATE_BLOB, CONFLICT);
520 		else
521 			*action = CHECKOUT_ACTION_IF(SAFE, UPDATE_BLOB, NONE);
522 		break;
523 	case GIT_DELTA_TYPECHANGE: /* case 22, 23, 29, 30 */
524 		if (delta->old_file.mode == GIT_FILEMODE_TREE) {
525 			if (wd->mode == GIT_FILEMODE_TREE)
526 				/* either deleting items in old tree will delete the wd dir,
527 				 * or we'll get a conflict when we attempt blob update...
528 				 */
529 				*action = CHECKOUT_ACTION_IF(SAFE, UPDATE_BLOB, NONE);
530 			else if (wd->mode == GIT_FILEMODE_COMMIT) {
531 				/* workdir is possibly a "phantom" submodule - treat as a
532 				 * tree if the only submodule info came from the config
533 				 */
534 				if (submodule_is_config_only(data, wd->path))
535 					*action = CHECKOUT_ACTION_IF(SAFE, UPDATE_BLOB, NONE);
536 				else
537 					*action = CHECKOUT_ACTION_IF(FORCE, REMOVE_AND_UPDATE, CONFLICT);
538 			} else
539 				*action = CHECKOUT_ACTION_IF(FORCE, REMOVE, CONFLICT);
540 		}
541 		else if (checkout_is_workdir_modified(data, &delta->old_file, &delta->new_file, wd))
542 			*action = CHECKOUT_ACTION_IF(FORCE, REMOVE_AND_UPDATE, CONFLICT);
543 		else
544 			*action = CHECKOUT_ACTION_IF(SAFE, REMOVE_AND_UPDATE, NONE);
545 
546 		/* don't update if the typechange is to a tree */
547 		if (delta->new_file.mode == GIT_FILEMODE_TREE)
548 			*action = (*action & ~CHECKOUT_ACTION__UPDATE_BLOB);
549 		break;
550 	default: /* impossible */
551 		break;
552 	}
553 
554 	return checkout_action_common(action, data, delta, wd);
555 }
556 
checkout_action_with_wd_blocker(int * action,checkout_data * data,const git_diff_delta * delta,const git_index_entry * wd)557 static int checkout_action_with_wd_blocker(
558 	int *action,
559 	checkout_data *data,
560 	const git_diff_delta *delta,
561 	const git_index_entry *wd)
562 {
563 	*action = CHECKOUT_ACTION__NONE;
564 
565 	switch (delta->status) {
566 	case GIT_DELTA_UNMODIFIED:
567 		/* should show delta as dirty / deleted */
568 		GIT_ERROR_CHECK_ERROR(
569 			checkout_notify(data, GIT_CHECKOUT_NOTIFY_DIRTY, delta, wd) );
570 		*action = CHECKOUT_ACTION_IF(FORCE, REMOVE_AND_UPDATE, NONE);
571 		break;
572 	case GIT_DELTA_ADDED:
573 	case GIT_DELTA_MODIFIED:
574 		*action = CHECKOUT_ACTION_IF(FORCE, REMOVE_AND_UPDATE, CONFLICT);
575 		break;
576 	case GIT_DELTA_DELETED:
577 		*action = CHECKOUT_ACTION_IF(FORCE, REMOVE, CONFLICT);
578 		break;
579 	case GIT_DELTA_TYPECHANGE:
580 		/* not 100% certain about this... */
581 		*action = CHECKOUT_ACTION_IF(FORCE, REMOVE_AND_UPDATE, CONFLICT);
582 		break;
583 	default: /* impossible */
584 		break;
585 	}
586 
587 	return checkout_action_common(action, data, delta, wd);
588 }
589 
checkout_action_with_wd_dir(int * action,checkout_data * data,const git_diff_delta * delta,git_iterator * workdir,const git_index_entry * wd)590 static int checkout_action_with_wd_dir(
591 	int *action,
592 	checkout_data *data,
593 	const git_diff_delta *delta,
594 	git_iterator *workdir,
595 	const git_index_entry *wd)
596 {
597 	*action = CHECKOUT_ACTION__NONE;
598 
599 	switch (delta->status) {
600 	case GIT_DELTA_UNMODIFIED: /* case 19 or 24 (or 34 but not really) */
601 		GIT_ERROR_CHECK_ERROR(
602 			checkout_notify(data, GIT_CHECKOUT_NOTIFY_DIRTY, delta, NULL));
603 		GIT_ERROR_CHECK_ERROR(
604 			checkout_notify(data, GIT_CHECKOUT_NOTIFY_UNTRACKED, NULL, wd));
605 		*action = CHECKOUT_ACTION_IF(FORCE, REMOVE_AND_UPDATE, NONE);
606 		break;
607 	case GIT_DELTA_ADDED:/* case 4 (and 7 for dir) */
608 	case GIT_DELTA_MODIFIED: /* case 20 (or 37 but not really) */
609 		if (delta->old_file.mode == GIT_FILEMODE_COMMIT)
610 			/* expected submodule (and maybe found one) */;
611 		else if (delta->new_file.mode != GIT_FILEMODE_TREE)
612 			*action = git_iterator_current_is_ignored(workdir) ?
613 				CHECKOUT_ACTION_IF(DONT_OVERWRITE_IGNORED, CONFLICT, REMOVE_AND_UPDATE) :
614 				CHECKOUT_ACTION_IF(FORCE, REMOVE_AND_UPDATE, CONFLICT);
615 		break;
616 	case GIT_DELTA_DELETED: /* case 11 (and 27 for dir) */
617 		if (delta->old_file.mode != GIT_FILEMODE_TREE)
618 			GIT_ERROR_CHECK_ERROR(
619 				checkout_notify(data, GIT_CHECKOUT_NOTIFY_UNTRACKED, NULL, wd));
620 		break;
621 	case GIT_DELTA_TYPECHANGE: /* case 24 or 31 */
622 		if (delta->old_file.mode == GIT_FILEMODE_TREE) {
623 			/* For typechange from dir, remove dir and add blob, but it is
624 			 * not safe to remove dir if it contains modified files.
625 			 * However, safely removing child files will remove the parent
626 			 * directory if is it left empty, so we can defer removing the
627 			 * dir and it will succeed if no children are left.
628 			 */
629 			*action = CHECKOUT_ACTION_IF(SAFE, UPDATE_BLOB, NONE);
630 		}
631 		else if (delta->new_file.mode != GIT_FILEMODE_TREE)
632 			/* For typechange to dir, dir is already created so no action */
633 			*action = CHECKOUT_ACTION_IF(FORCE, REMOVE_AND_UPDATE, CONFLICT);
634 		break;
635 	default: /* impossible */
636 		break;
637 	}
638 
639 	return checkout_action_common(action, data, delta, wd);
640 }
641 
checkout_action_with_wd_dir_empty(int * action,checkout_data * data,const git_diff_delta * delta)642 static int checkout_action_with_wd_dir_empty(
643 	int *action,
644 	checkout_data *data,
645 	const git_diff_delta *delta)
646 {
647 	int error = checkout_action_no_wd(action, data, delta);
648 
649 	/* We can always safely remove an empty directory. */
650 	if (error == 0 && *action != CHECKOUT_ACTION__NONE)
651 		*action |= CHECKOUT_ACTION__REMOVE;
652 
653 	return error;
654 }
655 
checkout_action(int * action,checkout_data * data,git_diff_delta * delta,git_iterator * workdir,const git_index_entry ** wditem,git_vector * pathspec)656 static int checkout_action(
657 	int *action,
658 	checkout_data *data,
659 	git_diff_delta *delta,
660 	git_iterator *workdir,
661 	const git_index_entry **wditem,
662 	git_vector *pathspec)
663 {
664 	int cmp = -1, error;
665 	int (*strcomp)(const char *, const char *) = data->diff->strcomp;
666 	int (*pfxcomp)(const char *str, const char *pfx) = data->diff->pfxcomp;
667 	int (*advance)(const git_index_entry **, git_iterator *) = NULL;
668 
669 	/* move workdir iterator to follow along with deltas */
670 
671 	while (1) {
672 		const git_index_entry *wd = *wditem;
673 
674 		if (!wd)
675 			return checkout_action_no_wd(action, data, delta);
676 
677 		cmp = strcomp(wd->path, delta->old_file.path);
678 
679 		/* 1. wd before delta ("a/a" before "a/b")
680 		 * 2. wd prefixes delta & should expand ("a/" before "a/b")
681 		 * 3. wd prefixes delta & cannot expand ("a/b" before "a/b/c")
682 		 * 4. wd equals delta ("a/b" and "a/b")
683 		 * 5. wd after delta & delta prefixes wd ("a/b/c" after "a/b/" or "a/b")
684 		 * 6. wd after delta ("a/c" after "a/b")
685 		 */
686 
687 		if (cmp < 0) {
688 			cmp = pfxcomp(delta->old_file.path, wd->path);
689 
690 			if (cmp == 0) {
691 				if (wd->mode == GIT_FILEMODE_TREE) {
692 					/* case 2 - entry prefixed by workdir tree */
693 					error = git_iterator_advance_into(wditem, workdir);
694 					if (error < 0 && error != GIT_ITEROVER)
695 						goto done;
696 					continue;
697 				}
698 
699 				/* case 3 maybe - wd contains non-dir where dir expected */
700 				if (delta->old_file.path[strlen(wd->path)] == '/') {
701 					error = checkout_action_with_wd_blocker(
702 						action, data, delta, wd);
703 					advance = git_iterator_advance;
704 					goto done;
705 				}
706 			}
707 
708 			/* case 1 - handle wd item (if it matches pathspec) */
709 			error = checkout_action_wd_only(data, workdir, wditem, pathspec);
710 			if (error && error != GIT_ITEROVER)
711 				goto done;
712 			continue;
713 		}
714 
715 		if (cmp == 0) {
716 			/* case 4 */
717 			error = checkout_action_with_wd(action, data, delta, workdir, wd);
718 			advance = git_iterator_advance;
719 			goto done;
720 		}
721 
722 		cmp = pfxcomp(wd->path, delta->old_file.path);
723 
724 		if (cmp == 0) { /* case 5 */
725 			if (wd->path[strlen(delta->old_file.path)] != '/')
726 				return checkout_action_no_wd(action, data, delta);
727 
728 			if (delta->status == GIT_DELTA_TYPECHANGE) {
729 				if (delta->old_file.mode == GIT_FILEMODE_TREE) {
730 					error = checkout_action_with_wd(action, data, delta, workdir, wd);
731 					advance = git_iterator_advance_into;
732 					goto done;
733 				}
734 
735 				if (delta->new_file.mode == GIT_FILEMODE_TREE ||
736 					delta->new_file.mode == GIT_FILEMODE_COMMIT ||
737 					delta->old_file.mode == GIT_FILEMODE_COMMIT)
738 				{
739 					error = checkout_action_with_wd(action, data, delta, workdir, wd);
740 					advance = git_iterator_advance;
741 					goto done;
742 				}
743 			}
744 
745 			return checkout_is_empty_dir(data, wd->path) ?
746 				checkout_action_with_wd_dir_empty(action, data, delta) :
747 				checkout_action_with_wd_dir(action, data, delta, workdir, wd);
748 		}
749 
750 		/* case 6 - wd is after delta */
751 		return checkout_action_no_wd(action, data, delta);
752 	}
753 
754 done:
755 	if (!error && advance != NULL &&
756 		(error = advance(wditem, workdir)) < 0) {
757 		*wditem = NULL;
758 		if (error == GIT_ITEROVER)
759 			error = 0;
760 	}
761 
762 	return error;
763 }
764 
checkout_remaining_wd_items(checkout_data * data,git_iterator * workdir,const git_index_entry * wd,git_vector * spec)765 static int checkout_remaining_wd_items(
766 	checkout_data *data,
767 	git_iterator *workdir,
768 	const git_index_entry *wd,
769 	git_vector *spec)
770 {
771 	int error = 0;
772 
773 	while (wd && !error)
774 		error = checkout_action_wd_only(data, workdir, &wd, spec);
775 
776 	if (error == GIT_ITEROVER)
777 		error = 0;
778 
779 	return error;
780 }
781 
checkout_idxentry_cmp(const git_index_entry * a,const git_index_entry * b)782 GIT_INLINE(int) checkout_idxentry_cmp(
783 	const git_index_entry *a,
784 	const git_index_entry *b)
785 {
786 	if (!a && !b)
787 		return 0;
788 	else if (!a && b)
789 		return -1;
790 	else if(a && !b)
791 		return 1;
792 	else
793 		return strcmp(a->path, b->path);
794 }
795 
checkout_conflictdata_cmp(const void * a,const void * b)796 static int checkout_conflictdata_cmp(const void *a, const void *b)
797 {
798 	const checkout_conflictdata *ca = a;
799 	const checkout_conflictdata *cb = b;
800 	int diff;
801 
802 	if ((diff = checkout_idxentry_cmp(ca->ancestor, cb->ancestor)) == 0 &&
803 	    (diff = checkout_idxentry_cmp(ca->ours, cb->theirs)) == 0)
804 		diff = checkout_idxentry_cmp(ca->theirs, cb->theirs);
805 
806 	return diff;
807 }
808 
checkout_conflictdata_empty(const git_vector * conflicts,size_t idx,void * payload)809 static int checkout_conflictdata_empty(
810 	const git_vector *conflicts, size_t idx, void *payload)
811 {
812 	checkout_conflictdata *conflict;
813 
814 	GIT_UNUSED(payload);
815 
816 	if ((conflict = git_vector_get(conflicts, idx)) == NULL)
817 		return -1;
818 
819 	if (conflict->ancestor || conflict->ours || conflict->theirs)
820 		return 0;
821 
822 	git__free(conflict);
823 	return 1;
824 }
825 
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)826 GIT_INLINE(bool) conflict_pathspec_match(
827 	checkout_data *data,
828 	git_iterator *workdir,
829 	git_vector *pathspec,
830 	const git_index_entry *ancestor,
831 	const git_index_entry *ours,
832 	const git_index_entry *theirs)
833 {
834 	/* if the pathspec matches ours *or* theirs, proceed */
835 	if (ours && git_pathspec__match(pathspec, ours->path,
836 		(data->strategy & GIT_CHECKOUT_DISABLE_PATHSPEC_MATCH) != 0,
837 		git_iterator_ignore_case(workdir), NULL, NULL))
838 		return true;
839 
840 	if (theirs && git_pathspec__match(pathspec, theirs->path,
841 		(data->strategy & GIT_CHECKOUT_DISABLE_PATHSPEC_MATCH) != 0,
842 		git_iterator_ignore_case(workdir), NULL, NULL))
843 		return true;
844 
845 	if (ancestor && git_pathspec__match(pathspec, ancestor->path,
846 		(data->strategy & GIT_CHECKOUT_DISABLE_PATHSPEC_MATCH) != 0,
847 		git_iterator_ignore_case(workdir), NULL, NULL))
848 		return true;
849 
850 	return false;
851 }
852 
checkout_conflict_detect_submodule(checkout_conflictdata * conflict)853 GIT_INLINE(int) checkout_conflict_detect_submodule(checkout_conflictdata *conflict)
854 {
855 	conflict->submodule = ((conflict->ancestor && S_ISGITLINK(conflict->ancestor->mode)) ||
856 		(conflict->ours && S_ISGITLINK(conflict->ours->mode)) ||
857 		(conflict->theirs && S_ISGITLINK(conflict->theirs->mode)));
858 	return 0;
859 }
860 
checkout_conflict_detect_binary(git_repository * repo,checkout_conflictdata * conflict)861 GIT_INLINE(int) checkout_conflict_detect_binary(git_repository *repo, checkout_conflictdata *conflict)
862 {
863 	git_blob *ancestor_blob = NULL, *our_blob = NULL, *their_blob = NULL;
864 	int error = 0;
865 
866 	if (conflict->submodule)
867 		return 0;
868 
869 	if (conflict->ancestor) {
870 		if ((error = git_blob_lookup(&ancestor_blob, repo, &conflict->ancestor->id)) < 0)
871 			goto done;
872 
873 		conflict->binary = git_blob_is_binary(ancestor_blob);
874 	}
875 
876 	if (!conflict->binary && conflict->ours) {
877 		if ((error = git_blob_lookup(&our_blob, repo, &conflict->ours->id)) < 0)
878 			goto done;
879 
880 		conflict->binary = git_blob_is_binary(our_blob);
881 	}
882 
883 	if (!conflict->binary && conflict->theirs) {
884 		if ((error = git_blob_lookup(&their_blob, repo, &conflict->theirs->id)) < 0)
885 			goto done;
886 
887 		conflict->binary = git_blob_is_binary(their_blob);
888 	}
889 
890 done:
891 	git_blob_free(ancestor_blob);
892 	git_blob_free(our_blob);
893 	git_blob_free(their_blob);
894 
895 	return error;
896 }
897 
checkout_conflict_append_update(const git_index_entry * ancestor,const git_index_entry * ours,const git_index_entry * theirs,void * payload)898 static int checkout_conflict_append_update(
899 	const git_index_entry *ancestor,
900 	const git_index_entry *ours,
901 	const git_index_entry *theirs,
902 	void *payload)
903 {
904 	checkout_data *data = payload;
905 	checkout_conflictdata *conflict;
906 	int error;
907 
908 	conflict = git__calloc(1, sizeof(checkout_conflictdata));
909 	GIT_ERROR_CHECK_ALLOC(conflict);
910 
911 	conflict->ancestor = ancestor;
912 	conflict->ours = ours;
913 	conflict->theirs = theirs;
914 
915 	if ((error = checkout_conflict_detect_submodule(conflict)) < 0 ||
916 		(error = checkout_conflict_detect_binary(data->repo, conflict)) < 0)
917 	{
918 		git__free(conflict);
919 		return error;
920 	}
921 
922 	if (git_vector_insert(&data->update_conflicts, conflict))
923 		return -1;
924 
925 	return 0;
926 }
927 
checkout_conflicts_foreach(checkout_data * data,git_index * index,git_iterator * workdir,git_vector * pathspec,int (* cb)(const git_index_entry *,const git_index_entry *,const git_index_entry *,void *),void * payload)928 static int checkout_conflicts_foreach(
929 	checkout_data *data,
930 	git_index *index,
931 	git_iterator *workdir,
932 	git_vector *pathspec,
933 	int (*cb)(const git_index_entry *, const git_index_entry *, const git_index_entry *, void *),
934 	void *payload)
935 {
936 	git_index_conflict_iterator *iterator = NULL;
937 	const git_index_entry *ancestor, *ours, *theirs;
938 	int error = 0;
939 
940 	if ((error = git_index_conflict_iterator_new(&iterator, index)) < 0)
941 		goto done;
942 
943 	/* Collect the conflicts */
944 	while ((error = git_index_conflict_next(&ancestor, &ours, &theirs, iterator)) == 0) {
945 		if (!conflict_pathspec_match(data, workdir, pathspec, ancestor, ours, theirs))
946 			continue;
947 
948 		if ((error = cb(ancestor, ours, theirs, payload)) < 0)
949 			goto done;
950 	}
951 
952 	if (error == GIT_ITEROVER)
953 		error = 0;
954 
955 done:
956 	git_index_conflict_iterator_free(iterator);
957 
958 	return error;
959 }
960 
checkout_conflicts_load(checkout_data * data,git_iterator * workdir,git_vector * pathspec)961 static int checkout_conflicts_load(checkout_data *data, git_iterator *workdir, git_vector *pathspec)
962 {
963 	git_index *index;
964 
965 	/* Only write conficts from sources that have them: indexes. */
966 	if ((index = git_iterator_index(data->target)) == NULL)
967 		return 0;
968 
969 	data->update_conflicts._cmp = checkout_conflictdata_cmp;
970 
971 	if (checkout_conflicts_foreach(data, index, workdir, pathspec, checkout_conflict_append_update, data) < 0)
972 		return -1;
973 
974 	/* Collect the REUC and NAME entries */
975 	data->update_reuc = &index->reuc;
976 	data->update_names = &index->names;
977 
978 	return 0;
979 }
980 
checkout_conflicts_cmp_entry(const char * path,const git_index_entry * entry)981 GIT_INLINE(int) checkout_conflicts_cmp_entry(
982 	const char *path,
983 	const git_index_entry *entry)
984 {
985 	return strcmp((const char *)path, entry->path);
986 }
987 
checkout_conflicts_cmp_ancestor(const void * p,const void * c)988 static int checkout_conflicts_cmp_ancestor(const void *p, const void *c)
989 {
990 	const char *path = p;
991 	const checkout_conflictdata *conflict = c;
992 
993 	if (!conflict->ancestor)
994 		return 1;
995 
996 	return checkout_conflicts_cmp_entry(path, conflict->ancestor);
997 }
998 
checkout_conflicts_search_ancestor(checkout_data * data,const char * path)999 static checkout_conflictdata *checkout_conflicts_search_ancestor(
1000 	checkout_data *data,
1001 	const char *path)
1002 {
1003 	size_t pos;
1004 
1005 	if (git_vector_bsearch2(&pos, &data->update_conflicts, checkout_conflicts_cmp_ancestor, path) < 0)
1006 		return NULL;
1007 
1008 	return git_vector_get(&data->update_conflicts, pos);
1009 }
1010 
checkout_conflicts_search_branch(checkout_data * data,const char * path)1011 static checkout_conflictdata *checkout_conflicts_search_branch(
1012 	checkout_data *data,
1013 	const char *path)
1014 {
1015 	checkout_conflictdata *conflict;
1016 	size_t i;
1017 
1018 	git_vector_foreach(&data->update_conflicts, i, conflict) {
1019 		int cmp = -1;
1020 
1021 		if (conflict->ancestor)
1022 			break;
1023 
1024 		if (conflict->ours)
1025 			cmp = checkout_conflicts_cmp_entry(path, conflict->ours);
1026 		else if (conflict->theirs)
1027 			cmp = checkout_conflicts_cmp_entry(path, conflict->theirs);
1028 
1029 		if (cmp == 0)
1030 			return conflict;
1031 	}
1032 
1033 	return NULL;
1034 }
1035 
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)1036 static int checkout_conflicts_load_byname_entry(
1037 	checkout_conflictdata **ancestor_out,
1038 	checkout_conflictdata **ours_out,
1039 	checkout_conflictdata **theirs_out,
1040 	checkout_data *data,
1041 	const git_index_name_entry *name_entry)
1042 {
1043 	checkout_conflictdata *ancestor, *ours = NULL, *theirs = NULL;
1044 	int error = 0;
1045 
1046 	*ancestor_out = NULL;
1047 	*ours_out = NULL;
1048 	*theirs_out = NULL;
1049 
1050 	if (!name_entry->ancestor) {
1051 		git_error_set(GIT_ERROR_INDEX, "a NAME entry exists without an ancestor");
1052 		error = -1;
1053 		goto done;
1054 	}
1055 
1056 	if (!name_entry->ours && !name_entry->theirs) {
1057 		git_error_set(GIT_ERROR_INDEX, "a NAME entry exists without an ours or theirs");
1058 		error = -1;
1059 		goto done;
1060 	}
1061 
1062 	if ((ancestor = checkout_conflicts_search_ancestor(data,
1063 		name_entry->ancestor)) == NULL) {
1064 		git_error_set(GIT_ERROR_INDEX,
1065 			"a NAME entry referenced ancestor entry '%s' which does not exist in the main index",
1066 			name_entry->ancestor);
1067 		error = -1;
1068 		goto done;
1069 	}
1070 
1071 	if (name_entry->ours) {
1072 		if (strcmp(name_entry->ancestor, name_entry->ours) == 0)
1073 			ours = ancestor;
1074 		else if ((ours = checkout_conflicts_search_branch(data, name_entry->ours)) == NULL ||
1075 			ours->ours == NULL) {
1076 			git_error_set(GIT_ERROR_INDEX,
1077 				"a NAME entry referenced our entry '%s' which does not exist in the main index",
1078 				name_entry->ours);
1079 			error = -1;
1080 			goto done;
1081 		}
1082 	}
1083 
1084 	if (name_entry->theirs) {
1085 		if (strcmp(name_entry->ancestor, name_entry->theirs) == 0)
1086 			theirs = ancestor;
1087 		else if (name_entry->ours && strcmp(name_entry->ours, name_entry->theirs) == 0)
1088 			theirs = ours;
1089 		else if ((theirs = checkout_conflicts_search_branch(data, name_entry->theirs)) == NULL ||
1090 			theirs->theirs == NULL) {
1091 			git_error_set(GIT_ERROR_INDEX,
1092 				"a NAME entry referenced their entry '%s' which does not exist in the main index",
1093 				name_entry->theirs);
1094 			error = -1;
1095 			goto done;
1096 		}
1097 	}
1098 
1099 	*ancestor_out = ancestor;
1100 	*ours_out = ours;
1101 	*theirs_out = theirs;
1102 
1103 done:
1104 	return error;
1105 }
1106 
checkout_conflicts_coalesce_renames(checkout_data * data)1107 static int checkout_conflicts_coalesce_renames(
1108 	checkout_data *data)
1109 {
1110 	git_index *index;
1111 	const git_index_name_entry *name_entry;
1112 	checkout_conflictdata *ancestor_conflict, *our_conflict, *their_conflict;
1113 	size_t i, names;
1114 	int error = 0;
1115 
1116 	if ((index = git_iterator_index(data->target)) == NULL)
1117 		return 0;
1118 
1119 	/* Juggle entries based on renames */
1120 	names = git_index_name_entrycount(index);
1121 
1122 	for (i = 0; i < names; i++) {
1123 		name_entry = git_index_name_get_byindex(index, i);
1124 
1125 		if ((error = checkout_conflicts_load_byname_entry(
1126 			&ancestor_conflict, &our_conflict, &their_conflict,
1127 			data, name_entry)) < 0)
1128 			goto done;
1129 
1130 		if (our_conflict && our_conflict != ancestor_conflict) {
1131 			ancestor_conflict->ours = our_conflict->ours;
1132 			our_conflict->ours = NULL;
1133 
1134 			if (our_conflict->theirs)
1135 				our_conflict->name_collision = 1;
1136 
1137 			if (our_conflict->name_collision)
1138 				ancestor_conflict->name_collision = 1;
1139 		}
1140 
1141 		if (their_conflict && their_conflict != ancestor_conflict) {
1142 			ancestor_conflict->theirs = their_conflict->theirs;
1143 			their_conflict->theirs = NULL;
1144 
1145 			if (their_conflict->ours)
1146 				their_conflict->name_collision = 1;
1147 
1148 			if (their_conflict->name_collision)
1149 				ancestor_conflict->name_collision = 1;
1150 		}
1151 
1152 		if (our_conflict && our_conflict != ancestor_conflict &&
1153 			their_conflict && their_conflict != ancestor_conflict)
1154 			ancestor_conflict->one_to_two = 1;
1155 	}
1156 
1157 	git_vector_remove_matching(
1158 		&data->update_conflicts, checkout_conflictdata_empty, NULL);
1159 
1160 done:
1161 	return error;
1162 }
1163 
checkout_conflicts_mark_directoryfile(checkout_data * data)1164 static int checkout_conflicts_mark_directoryfile(
1165 	checkout_data *data)
1166 {
1167 	git_index *index;
1168 	checkout_conflictdata *conflict;
1169 	const git_index_entry *entry;
1170 	size_t i, j, len;
1171 	const char *path;
1172 	int prefixed, error = 0;
1173 
1174 	if ((index = git_iterator_index(data->target)) == NULL)
1175 		return 0;
1176 
1177 	len = git_index_entrycount(index);
1178 
1179 	/* Find d/f conflicts */
1180 	git_vector_foreach(&data->update_conflicts, i, conflict) {
1181 		if ((conflict->ours && conflict->theirs) ||
1182 		    (!conflict->ours && !conflict->theirs))
1183 			continue;
1184 
1185 		path = conflict->ours ?
1186 			conflict->ours->path : conflict->theirs->path;
1187 
1188 		if ((error = git_index_find(&j, index, path)) < 0) {
1189 			if (error == GIT_ENOTFOUND)
1190 				git_error_set(GIT_ERROR_INDEX,
1191 					"index inconsistency, could not find entry for expected conflict '%s'", path);
1192 
1193 			goto done;
1194 		}
1195 
1196 		for (; j < len; j++) {
1197 			if ((entry = git_index_get_byindex(index, j)) == NULL) {
1198 				git_error_set(GIT_ERROR_INDEX,
1199 					"index inconsistency, truncated index while loading expected conflict '%s'", path);
1200 				error = -1;
1201 				goto done;
1202 			}
1203 
1204 			prefixed = git_path_equal_or_prefixed(path, entry->path, NULL);
1205 
1206 			if (prefixed == GIT_PATH_EQUAL)
1207 				continue;
1208 
1209 			if (prefixed == GIT_PATH_PREFIX)
1210 				conflict->directoryfile = 1;
1211 
1212 			break;
1213 		}
1214 	}
1215 
1216 done:
1217 	return error;
1218 }
1219 
checkout_get_update_conflicts(checkout_data * data,git_iterator * workdir,git_vector * pathspec)1220 static int checkout_get_update_conflicts(
1221 	checkout_data *data,
1222 	git_iterator *workdir,
1223 	git_vector *pathspec)
1224 {
1225 	int error = 0;
1226 
1227 	if (data->strategy & GIT_CHECKOUT_SKIP_UNMERGED)
1228 		return 0;
1229 
1230 	if ((error = checkout_conflicts_load(data, workdir, pathspec)) < 0 ||
1231 	    (error = checkout_conflicts_coalesce_renames(data)) < 0 ||
1232 	    (error = checkout_conflicts_mark_directoryfile(data)) < 0)
1233 		goto done;
1234 
1235 done:
1236 	return error;
1237 }
1238 
checkout_conflict_append_remove(const git_index_entry * ancestor,const git_index_entry * ours,const git_index_entry * theirs,void * payload)1239 static int checkout_conflict_append_remove(
1240 	const git_index_entry *ancestor,
1241 	const git_index_entry *ours,
1242 	const git_index_entry *theirs,
1243 	void *payload)
1244 {
1245 	checkout_data *data = payload;
1246 	const char *name;
1247 
1248 	GIT_ASSERT_ARG(ancestor || ours || theirs);
1249 
1250 	if (ancestor)
1251 		name = git__strdup(ancestor->path);
1252 	else if (ours)
1253 		name = git__strdup(ours->path);
1254 	else if (theirs)
1255 		name = git__strdup(theirs->path);
1256 	else
1257 		abort();
1258 
1259 	GIT_ERROR_CHECK_ALLOC(name);
1260 
1261 	return git_vector_insert(&data->remove_conflicts, (char *)name);
1262 }
1263 
checkout_get_remove_conflicts(checkout_data * data,git_iterator * workdir,git_vector * pathspec)1264 static int checkout_get_remove_conflicts(
1265 	checkout_data *data,
1266 	git_iterator *workdir,
1267 	git_vector *pathspec)
1268 {
1269 	if ((data->strategy & GIT_CHECKOUT_DONT_UPDATE_INDEX) != 0)
1270 		return 0;
1271 
1272 	return checkout_conflicts_foreach(data, data->index, workdir, pathspec, checkout_conflict_append_remove, data);
1273 }
1274 
checkout_verify_paths(git_repository * repo,int action,git_diff_delta * delta)1275 static int checkout_verify_paths(
1276 	git_repository *repo,
1277 	int action,
1278 	git_diff_delta *delta)
1279 {
1280 	unsigned int flags = GIT_PATH_REJECT_WORKDIR_DEFAULTS;
1281 
1282 	if (action & CHECKOUT_ACTION__REMOVE) {
1283 		if (!git_path_validate(repo, delta->old_file.path, delta->old_file.mode, flags)) {
1284 			git_error_set(GIT_ERROR_CHECKOUT, "cannot remove invalid path '%s'", delta->old_file.path);
1285 			return -1;
1286 		}
1287 	}
1288 
1289 	if (action & ~CHECKOUT_ACTION__REMOVE) {
1290 		if (!git_path_validate(repo, delta->new_file.path, delta->new_file.mode, flags)) {
1291 			git_error_set(GIT_ERROR_CHECKOUT, "cannot checkout to invalid path '%s'", delta->new_file.path);
1292 			return -1;
1293 		}
1294 	}
1295 
1296 	return 0;
1297 }
1298 
checkout_get_actions(uint32_t ** actions_ptr,size_t ** counts_ptr,checkout_data * data,git_iterator * workdir)1299 static int checkout_get_actions(
1300 	uint32_t **actions_ptr,
1301 	size_t **counts_ptr,
1302 	checkout_data *data,
1303 	git_iterator *workdir)
1304 {
1305 	int error = 0, act;
1306 	const git_index_entry *wditem;
1307 	git_vector pathspec = GIT_VECTOR_INIT, *deltas;
1308 	git_pool pathpool;
1309 	git_diff_delta *delta;
1310 	size_t i, *counts = NULL;
1311 	uint32_t *actions = NULL;
1312 
1313 	if (git_pool_init(&pathpool, 1) < 0)
1314 		return -1;
1315 
1316 	if (data->opts.paths.count > 0 &&
1317 	    git_pathspec__vinit(&pathspec, &data->opts.paths, &pathpool) < 0)
1318 		return -1;
1319 
1320 	if ((error = git_iterator_current(&wditem, workdir)) < 0 &&
1321 	    error != GIT_ITEROVER)
1322 		goto fail;
1323 
1324 	deltas = &data->diff->deltas;
1325 
1326 	*counts_ptr = counts = git__calloc(CHECKOUT_ACTION__MAX+1, sizeof(size_t));
1327 	*actions_ptr = actions = git__calloc(
1328 		deltas->length ? deltas->length : 1, sizeof(uint32_t));
1329 	if (!counts || !actions) {
1330 		error = -1;
1331 		goto fail;
1332 	}
1333 
1334 	git_vector_foreach(deltas, i, delta) {
1335 		if ((error = checkout_action(&act, data, delta, workdir, &wditem, &pathspec)) == 0)
1336 			error = checkout_verify_paths(data->repo, act, delta);
1337 
1338 		if (error != 0)
1339 			goto fail;
1340 
1341 		actions[i] = act;
1342 
1343 		if (act & CHECKOUT_ACTION__REMOVE)
1344 			counts[CHECKOUT_ACTION__REMOVE]++;
1345 		if (act & CHECKOUT_ACTION__UPDATE_BLOB)
1346 			counts[CHECKOUT_ACTION__UPDATE_BLOB]++;
1347 		if (act & CHECKOUT_ACTION__UPDATE_SUBMODULE)
1348 			counts[CHECKOUT_ACTION__UPDATE_SUBMODULE]++;
1349 		if (act & CHECKOUT_ACTION__CONFLICT)
1350 			counts[CHECKOUT_ACTION__CONFLICT]++;
1351 	}
1352 
1353 	error = checkout_remaining_wd_items(data, workdir, wditem, &pathspec);
1354 	if (error)
1355 		goto fail;
1356 
1357 	counts[CHECKOUT_ACTION__REMOVE] += data->removes.length;
1358 
1359 	if (counts[CHECKOUT_ACTION__CONFLICT] > 0 &&
1360 	    (data->strategy & GIT_CHECKOUT_ALLOW_CONFLICTS) == 0) {
1361 		git_error_set(GIT_ERROR_CHECKOUT, "%"PRIuZ" %s checkout",
1362 			counts[CHECKOUT_ACTION__CONFLICT],
1363 			counts[CHECKOUT_ACTION__CONFLICT] == 1 ?
1364 			"conflict prevents" : "conflicts prevent");
1365 		error = GIT_ECONFLICT;
1366 		goto fail;
1367 	}
1368 
1369 
1370 	if ((error = checkout_get_remove_conflicts(data, workdir, &pathspec)) < 0 ||
1371 	    (error = checkout_get_update_conflicts(data, workdir, &pathspec)) < 0)
1372 		goto fail;
1373 
1374 	counts[CHECKOUT_ACTION__REMOVE_CONFLICT] = git_vector_length(&data->remove_conflicts);
1375 	counts[CHECKOUT_ACTION__UPDATE_CONFLICT] = git_vector_length(&data->update_conflicts);
1376 
1377 	git_pathspec__vfree(&pathspec);
1378 	git_pool_clear(&pathpool);
1379 
1380 	return 0;
1381 
1382 fail:
1383 	*counts_ptr = NULL;
1384 	git__free(counts);
1385 	*actions_ptr = NULL;
1386 	git__free(actions);
1387 
1388 	git_pathspec__vfree(&pathspec);
1389 	git_pool_clear(&pathpool);
1390 
1391 	return error;
1392 }
1393 
should_remove_existing(checkout_data * data)1394 static bool should_remove_existing(checkout_data *data)
1395 {
1396 	int ignorecase;
1397 
1398 	if (git_repository__configmap_lookup(&ignorecase, data->repo, GIT_CONFIGMAP_IGNORECASE) < 0) {
1399 		ignorecase = 0;
1400 	}
1401 
1402 	return (ignorecase &&
1403 		(data->strategy & GIT_CHECKOUT_DONT_REMOVE_EXISTING) == 0);
1404 }
1405 
1406 #define MKDIR_NORMAL \
1407 	GIT_MKDIR_PATH | GIT_MKDIR_VERIFY_DIR
1408 #define MKDIR_REMOVE_EXISTING \
1409 	MKDIR_NORMAL | GIT_MKDIR_REMOVE_FILES | GIT_MKDIR_REMOVE_SYMLINKS
1410 
checkout_mkdir(checkout_data * data,const char * path,const char * base,mode_t mode,unsigned int flags)1411 static int checkout_mkdir(
1412 	checkout_data *data,
1413 	const char *path,
1414 	const char *base,
1415 	mode_t mode,
1416 	unsigned int flags)
1417 {
1418 	struct git_futils_mkdir_options mkdir_opts = {0};
1419 	int error;
1420 
1421 	mkdir_opts.dir_map = data->mkdir_map;
1422 	mkdir_opts.pool = &data->pool;
1423 
1424 	error = git_futils_mkdir_relative(
1425 		path, base, mode, flags, &mkdir_opts);
1426 
1427 	data->perfdata.mkdir_calls += mkdir_opts.perfdata.mkdir_calls;
1428 	data->perfdata.stat_calls += mkdir_opts.perfdata.stat_calls;
1429 	data->perfdata.chmod_calls += mkdir_opts.perfdata.chmod_calls;
1430 
1431 	return error;
1432 }
1433 
mkpath2file(checkout_data * data,const char * path,unsigned int mode)1434 static int mkpath2file(
1435 	checkout_data *data, const char *path, unsigned int mode)
1436 {
1437 	struct stat st;
1438 	bool remove_existing = should_remove_existing(data);
1439 	unsigned int flags =
1440 		(remove_existing ? MKDIR_REMOVE_EXISTING : MKDIR_NORMAL) |
1441 		GIT_MKDIR_SKIP_LAST;
1442 	int error;
1443 
1444 	if ((error = checkout_mkdir(
1445 			data, path, data->opts.target_directory, mode, flags)) < 0)
1446 		return error;
1447 
1448 	if (remove_existing) {
1449 		data->perfdata.stat_calls++;
1450 
1451 		if (p_lstat(path, &st) == 0) {
1452 
1453 			/* Some file, symlink or folder already exists at this name.
1454 			 * We would have removed it in remove_the_old unless we're on
1455 			 * a case inensitive filesystem (or the user has asked us not
1456 			 * to).  Remove the similarly named file to write the new.
1457 			 */
1458 			error = git_futils_rmdir_r(path, NULL, GIT_RMDIR_REMOVE_FILES);
1459 		} else if (errno != ENOENT) {
1460 			git_error_set(GIT_ERROR_OS, "failed to stat '%s'", path);
1461 			return GIT_EEXISTS;
1462 		} else {
1463 			git_error_clear();
1464 		}
1465 	}
1466 
1467 	return error;
1468 }
1469 
1470 struct checkout_stream {
1471 	git_writestream base;
1472 	const char *path;
1473 	int fd;
1474 	int open;
1475 };
1476 
checkout_stream_write(git_writestream * s,const char * buffer,size_t len)1477 static int checkout_stream_write(
1478 	git_writestream *s, const char *buffer, size_t len)
1479 {
1480 	struct checkout_stream *stream = (struct checkout_stream *)s;
1481 	int ret;
1482 
1483 	if ((ret = p_write(stream->fd, buffer, len)) < 0)
1484 		git_error_set(GIT_ERROR_OS, "could not write to '%s'", stream->path);
1485 
1486 	return ret;
1487 }
1488 
checkout_stream_close(git_writestream * s)1489 static int checkout_stream_close(git_writestream *s)
1490 {
1491 	struct checkout_stream *stream = (struct checkout_stream *)s;
1492 
1493 	GIT_ASSERT_ARG(stream);
1494 	GIT_ASSERT_ARG(stream->open);
1495 
1496 	stream->open = 0;
1497 	return p_close(stream->fd);
1498 }
1499 
checkout_stream_free(git_writestream * s)1500 static void checkout_stream_free(git_writestream *s)
1501 {
1502 	GIT_UNUSED(s);
1503 }
1504 
blob_content_to_file(checkout_data * data,struct stat * st,git_blob * blob,const char * path,const char * hint_path,mode_t entry_filemode)1505 static int blob_content_to_file(
1506 	checkout_data *data,
1507 	struct stat *st,
1508 	git_blob *blob,
1509 	const char *path,
1510 	const char *hint_path,
1511 	mode_t entry_filemode)
1512 {
1513 	int flags = data->opts.file_open_flags;
1514 	mode_t file_mode = data->opts.file_mode ?
1515 		data->opts.file_mode : entry_filemode;
1516 	git_filter_options filter_opts = GIT_FILTER_OPTIONS_INIT;
1517 	struct checkout_stream writer;
1518 	mode_t mode;
1519 	git_filter_list *fl = NULL;
1520 	int fd;
1521 	int error = 0;
1522 
1523 	if (hint_path == NULL)
1524 		hint_path = path;
1525 
1526 	if ((error = mkpath2file(data, path, data->opts.dir_mode)) < 0)
1527 		return error;
1528 
1529 	if (flags <= 0)
1530 		flags = O_CREAT | O_TRUNC | O_WRONLY;
1531 	if (!(mode = file_mode))
1532 		mode = GIT_FILEMODE_BLOB;
1533 
1534 	if ((fd = p_open(path, flags, mode)) < 0) {
1535 		git_error_set(GIT_ERROR_OS, "could not open '%s' for writing", path);
1536 		return fd;
1537 	}
1538 
1539 	filter_opts.attr_session = &data->attr_session;
1540 	filter_opts.temp_buf = &data->tmp;
1541 
1542 	if (!data->opts.disable_filters &&
1543 		(error = git_filter_list__load_ext(
1544 			&fl, data->repo, blob, hint_path,
1545 			GIT_FILTER_TO_WORKTREE, &filter_opts))) {
1546 		p_close(fd);
1547 		return error;
1548 	}
1549 
1550 	/* setup the writer */
1551 	memset(&writer, 0, sizeof(struct checkout_stream));
1552 	writer.base.write = checkout_stream_write;
1553 	writer.base.close = checkout_stream_close;
1554 	writer.base.free = checkout_stream_free;
1555 	writer.path = path;
1556 	writer.fd = fd;
1557 	writer.open = 1;
1558 
1559 	error = git_filter_list_stream_blob(fl, blob, &writer.base);
1560 
1561 	GIT_ASSERT(writer.open == 0);
1562 
1563 	git_filter_list_free(fl);
1564 
1565 	if (error < 0)
1566 		return error;
1567 
1568 	if (st) {
1569 		data->perfdata.stat_calls++;
1570 
1571 		if ((error = p_stat(path, st)) < 0) {
1572 			git_error_set(GIT_ERROR_OS, "failed to stat '%s'", path);
1573 			return error;
1574 		}
1575 
1576 		st->st_mode = entry_filemode;
1577 	}
1578 
1579 	return 0;
1580 }
1581 
blob_content_to_link(checkout_data * data,struct stat * st,git_blob * blob,const char * path)1582 static int blob_content_to_link(
1583 	checkout_data *data,
1584 	struct stat *st,
1585 	git_blob *blob,
1586 	const char *path)
1587 {
1588 	git_buf linktarget = GIT_BUF_INIT;
1589 	int error;
1590 
1591 	if ((error = mkpath2file(data, path, data->opts.dir_mode)) < 0)
1592 		return error;
1593 
1594 	if ((error = git_blob__getbuf(&linktarget, blob)) < 0)
1595 		return error;
1596 
1597 	if (data->can_symlink) {
1598 		if ((error = p_symlink(git_buf_cstr(&linktarget), path)) < 0)
1599 			git_error_set(GIT_ERROR_OS, "could not create symlink %s", path);
1600 	} else {
1601 		error = git_futils_fake_symlink(git_buf_cstr(&linktarget), path);
1602 	}
1603 
1604 	if (!error) {
1605 		data->perfdata.stat_calls++;
1606 
1607 		if ((error = p_lstat(path, st)) < 0)
1608 			git_error_set(GIT_ERROR_CHECKOUT, "could not stat symlink %s", path);
1609 
1610 		st->st_mode = GIT_FILEMODE_LINK;
1611 	}
1612 
1613 	git_buf_dispose(&linktarget);
1614 
1615 	return error;
1616 }
1617 
checkout_update_index(checkout_data * data,const git_diff_file * file,struct stat * st)1618 static int checkout_update_index(
1619 	checkout_data *data,
1620 	const git_diff_file *file,
1621 	struct stat *st)
1622 {
1623 	git_index_entry entry;
1624 
1625 	if (!data->index)
1626 		return 0;
1627 
1628 	memset(&entry, 0, sizeof(entry));
1629 	entry.path = (char *)file->path; /* cast to prevent warning */
1630 	git_index_entry__init_from_stat(&entry, st, true);
1631 	git_oid_cpy(&entry.id, &file->id);
1632 
1633 	return git_index_add(data->index, &entry);
1634 }
1635 
checkout_submodule_update_index(checkout_data * data,const git_diff_file * file)1636 static int checkout_submodule_update_index(
1637 	checkout_data *data,
1638 	const git_diff_file *file)
1639 {
1640 	git_buf *fullpath;
1641 	struct stat st;
1642 
1643 	/* update the index unless prevented */
1644 	if ((data->strategy & GIT_CHECKOUT_DONT_UPDATE_INDEX) != 0)
1645 		return 0;
1646 
1647 	if (checkout_target_fullpath(&fullpath, data, file->path) < 0)
1648 		return -1;
1649 
1650 	data->perfdata.stat_calls++;
1651 	if (p_stat(fullpath->ptr, &st) < 0) {
1652 		git_error_set(
1653 			GIT_ERROR_CHECKOUT, "could not stat submodule %s\n", file->path);
1654 		return GIT_ENOTFOUND;
1655 	}
1656 
1657 	st.st_mode = GIT_FILEMODE_COMMIT;
1658 
1659 	return checkout_update_index(data, file, &st);
1660 }
1661 
checkout_submodule(checkout_data * data,const git_diff_file * file)1662 static int checkout_submodule(
1663 	checkout_data *data,
1664 	const git_diff_file *file)
1665 {
1666 	bool remove_existing = should_remove_existing(data);
1667 	int error = 0;
1668 
1669 	/* Until submodules are supported, UPDATE_ONLY means do nothing here */
1670 	if ((data->strategy & GIT_CHECKOUT_UPDATE_ONLY) != 0)
1671 		return 0;
1672 
1673 	if ((error = checkout_mkdir(
1674 			data,
1675 			file->path, data->opts.target_directory, data->opts.dir_mode,
1676 			remove_existing ? MKDIR_REMOVE_EXISTING : MKDIR_NORMAL)) < 0)
1677 		return error;
1678 
1679 	if ((error = git_submodule_lookup(NULL, data->repo, file->path)) < 0) {
1680 		/* I've observed repos with submodules in the tree that do not
1681 		 * have a .gitmodules - core Git just makes an empty directory
1682 		 */
1683 		if (error == GIT_ENOTFOUND) {
1684 			git_error_clear();
1685 			return checkout_submodule_update_index(data, file);
1686 		}
1687 
1688 		return error;
1689 	}
1690 
1691 	/* TODO: Support checkout_strategy options.  Two circumstances:
1692 	 * 1 - submodule already checked out, but we need to move the HEAD
1693 	 *     to the new OID, or
1694 	 * 2 - submodule not checked out and we should recursively check it out
1695 	 *
1696 	 * Checkout will not execute a pull on the submodule, but a clone
1697 	 * command should probably be able to.  Do we need a submodule callback?
1698 	 */
1699 
1700 	return checkout_submodule_update_index(data, file);
1701 }
1702 
report_progress(checkout_data * data,const char * path)1703 static void report_progress(
1704 	checkout_data *data,
1705 	const char *path)
1706 {
1707 	if (data->opts.progress_cb)
1708 		data->opts.progress_cb(
1709 			path, data->completed_steps, data->total_steps,
1710 			data->opts.progress_payload);
1711 }
1712 
checkout_safe_for_update_only(checkout_data * data,const char * path,mode_t expected_mode)1713 static int checkout_safe_for_update_only(
1714 	checkout_data *data, const char *path, mode_t expected_mode)
1715 {
1716 	struct stat st;
1717 
1718 	data->perfdata.stat_calls++;
1719 
1720 	if (p_lstat(path, &st) < 0) {
1721 		/* if doesn't exist, then no error and no update */
1722 		if (errno == ENOENT || errno == ENOTDIR)
1723 			return 0;
1724 
1725 		/* otherwise, stat error and no update */
1726 		git_error_set(GIT_ERROR_OS, "failed to stat '%s'", path);
1727 		return -1;
1728 	}
1729 
1730 	/* only safe for update if this is the same type of file */
1731 	if ((st.st_mode & ~0777) == (expected_mode & ~0777))
1732 		return 1;
1733 
1734 	return 0;
1735 }
1736 
checkout_write_content(checkout_data * data,const git_oid * oid,const char * full_path,const char * hint_path,unsigned int mode,struct stat * st)1737 static int checkout_write_content(
1738 	checkout_data *data,
1739 	const git_oid *oid,
1740 	const char *full_path,
1741 	const char *hint_path,
1742 	unsigned int mode,
1743 	struct stat *st)
1744 {
1745 	int error = 0;
1746 	git_blob *blob;
1747 
1748 	if ((error = git_blob_lookup(&blob, data->repo, oid)) < 0)
1749 		return error;
1750 
1751 	if (S_ISLNK(mode))
1752 		error = blob_content_to_link(data, st, blob, full_path);
1753 	else
1754 		error = blob_content_to_file(data, st, blob, full_path, hint_path, mode);
1755 
1756 	git_blob_free(blob);
1757 
1758 	/* if we try to create the blob and an existing directory blocks it from
1759 	 * being written, then there must have been a typechange conflict in a
1760 	 * parent directory - suppress the error and try to continue.
1761 	 */
1762 	if ((data->strategy & GIT_CHECKOUT_ALLOW_CONFLICTS) != 0 &&
1763 		(error == GIT_ENOTFOUND || error == GIT_EEXISTS))
1764 	{
1765 		git_error_clear();
1766 		error = 0;
1767 	}
1768 
1769 	return error;
1770 }
1771 
checkout_blob(checkout_data * data,const git_diff_file * file)1772 static int checkout_blob(
1773 	checkout_data *data,
1774 	const git_diff_file *file)
1775 {
1776 	git_buf *fullpath;
1777 	struct stat st;
1778 	int error = 0;
1779 
1780 	if (checkout_target_fullpath(&fullpath, data, file->path) < 0)
1781 		return -1;
1782 
1783 	if ((data->strategy & GIT_CHECKOUT_UPDATE_ONLY) != 0) {
1784 		int rval = checkout_safe_for_update_only(
1785 			data, fullpath->ptr, file->mode);
1786 
1787 		if (rval <= 0)
1788 			return rval;
1789 	}
1790 
1791 	error = checkout_write_content(
1792 		data, &file->id, fullpath->ptr, NULL, file->mode, &st);
1793 
1794 	/* update the index unless prevented */
1795 	if (!error && (data->strategy & GIT_CHECKOUT_DONT_UPDATE_INDEX) == 0)
1796 		error = checkout_update_index(data, file, &st);
1797 
1798 	/* update the submodule data if this was a new .gitmodules file */
1799 	if (!error && strcmp(file->path, ".gitmodules") == 0)
1800 		data->reload_submodules = true;
1801 
1802 	return error;
1803 }
1804 
checkout_remove_the_old(unsigned int * actions,checkout_data * data)1805 static int checkout_remove_the_old(
1806 	unsigned int *actions,
1807 	checkout_data *data)
1808 {
1809 	int error = 0;
1810 	git_diff_delta *delta;
1811 	const char *str;
1812 	size_t i;
1813 	git_buf *fullpath;
1814 	uint32_t flg = GIT_RMDIR_EMPTY_PARENTS |
1815 		GIT_RMDIR_REMOVE_FILES | GIT_RMDIR_REMOVE_BLOCKERS;
1816 
1817 	if (data->opts.checkout_strategy & GIT_CHECKOUT_SKIP_LOCKED_DIRECTORIES)
1818 		flg |= GIT_RMDIR_SKIP_NONEMPTY;
1819 
1820 	if (checkout_target_fullpath(&fullpath, data, NULL) < 0)
1821 		return -1;
1822 
1823 	git_vector_foreach(&data->diff->deltas, i, delta) {
1824 		if (actions[i] & CHECKOUT_ACTION__REMOVE) {
1825 			error = git_futils_rmdir_r(
1826 				delta->old_file.path, fullpath->ptr, flg);
1827 
1828 			if (error < 0)
1829 				return error;
1830 
1831 			data->completed_steps++;
1832 			report_progress(data, delta->old_file.path);
1833 
1834 			if ((actions[i] & CHECKOUT_ACTION__UPDATE_BLOB) == 0 &&
1835 				(data->strategy & GIT_CHECKOUT_DONT_UPDATE_INDEX) == 0 &&
1836 				data->index != NULL)
1837 			{
1838 				(void)git_index_remove(data->index, delta->old_file.path, 0);
1839 			}
1840 		}
1841 	}
1842 
1843 	git_vector_foreach(&data->removes, i, str) {
1844 		error = git_futils_rmdir_r(str, fullpath->ptr, flg);
1845 		if (error < 0)
1846 			return error;
1847 
1848 		data->completed_steps++;
1849 		report_progress(data, str);
1850 
1851 		if ((data->strategy & GIT_CHECKOUT_DONT_UPDATE_INDEX) == 0 &&
1852 			data->index != NULL)
1853 		{
1854 			if (str[strlen(str) - 1] == '/')
1855 				(void)git_index_remove_directory(data->index, str, 0);
1856 			else
1857 				(void)git_index_remove(data->index, str, 0);
1858 		}
1859 	}
1860 
1861 	return 0;
1862 }
1863 
checkout_create_the_new(unsigned int * actions,checkout_data * data)1864 static int checkout_create_the_new(
1865 	unsigned int *actions,
1866 	checkout_data *data)
1867 {
1868 	int error = 0;
1869 	git_diff_delta *delta;
1870 	size_t i;
1871 
1872 	git_vector_foreach(&data->diff->deltas, i, delta) {
1873 		if (actions[i] & CHECKOUT_ACTION__UPDATE_BLOB && !S_ISLNK(delta->new_file.mode)) {
1874 			if ((error = checkout_blob(data, &delta->new_file)) < 0)
1875 				return error;
1876 			data->completed_steps++;
1877 			report_progress(data, delta->new_file.path);
1878 		}
1879 	}
1880 
1881 	git_vector_foreach(&data->diff->deltas, i, delta) {
1882 		if (actions[i] & CHECKOUT_ACTION__UPDATE_BLOB && S_ISLNK(delta->new_file.mode)) {
1883 			if ((error = checkout_blob(data, &delta->new_file)) < 0)
1884 				return error;
1885 			data->completed_steps++;
1886 			report_progress(data, delta->new_file.path);
1887 		}
1888 	}
1889 
1890 	return 0;
1891 }
1892 
checkout_create_submodules(unsigned int * actions,checkout_data * data)1893 static int checkout_create_submodules(
1894 	unsigned int *actions,
1895 	checkout_data *data)
1896 {
1897 	git_diff_delta *delta;
1898 	size_t i;
1899 
1900 	git_vector_foreach(&data->diff->deltas, i, delta) {
1901 		if (actions[i] & CHECKOUT_ACTION__UPDATE_SUBMODULE) {
1902 			int error = checkout_submodule(data, &delta->new_file);
1903 			if (error < 0)
1904 				return error;
1905 
1906 			data->completed_steps++;
1907 			report_progress(data, delta->new_file.path);
1908 		}
1909 	}
1910 
1911 	return 0;
1912 }
1913 
checkout_lookup_head_tree(git_tree ** out,git_repository * repo)1914 static int checkout_lookup_head_tree(git_tree **out, git_repository *repo)
1915 {
1916 	int error = 0;
1917 	git_reference *ref = NULL;
1918 	git_object *head;
1919 
1920 	if (!(error = git_repository_head(&ref, repo)) &&
1921 		!(error = git_reference_peel(&head, ref, GIT_OBJECT_TREE)))
1922 		*out = (git_tree *)head;
1923 
1924 	git_reference_free(ref);
1925 
1926 	return error;
1927 }
1928 
1929 
conflict_entry_name(git_buf * out,const char * side_name,const char * filename)1930 static int conflict_entry_name(
1931 	git_buf *out,
1932 	const char *side_name,
1933 	const char *filename)
1934 {
1935 	if (git_buf_puts(out, side_name) < 0 ||
1936 		git_buf_putc(out, ':') < 0 ||
1937 		git_buf_puts(out, filename) < 0)
1938 		return -1;
1939 
1940 	return 0;
1941 }
1942 
checkout_path_suffixed(git_buf * path,const char * suffix)1943 static int checkout_path_suffixed(git_buf *path, const char *suffix)
1944 {
1945 	size_t path_len;
1946 	int i = 0, error = 0;
1947 
1948 	if ((error = git_buf_putc(path, '~')) < 0 || (error = git_buf_puts(path, suffix)) < 0)
1949 		return -1;
1950 
1951 	path_len = git_buf_len(path);
1952 
1953 	while (git_path_exists(git_buf_cstr(path)) && i < INT_MAX) {
1954 		git_buf_truncate(path, path_len);
1955 
1956 		if ((error = git_buf_putc(path, '_')) < 0 ||
1957 			(error = git_buf_printf(path, "%d", i)) < 0)
1958 			return error;
1959 
1960 		i++;
1961 	}
1962 
1963 	if (i == INT_MAX) {
1964 		git_buf_truncate(path, path_len);
1965 
1966 		git_error_set(GIT_ERROR_CHECKOUT, "could not write '%s': working directory file exists", path->ptr);
1967 		return GIT_EEXISTS;
1968 	}
1969 
1970 	return 0;
1971 }
1972 
checkout_write_entry(checkout_data * data,checkout_conflictdata * conflict,const git_index_entry * side)1973 static int checkout_write_entry(
1974 	checkout_data *data,
1975 	checkout_conflictdata *conflict,
1976 	const git_index_entry *side)
1977 {
1978 	const char *hint_path = NULL, *suffix;
1979 	git_buf *fullpath;
1980 	struct stat st;
1981 	int error;
1982 
1983 	GIT_ASSERT(side == conflict->ours || side == conflict->theirs);
1984 
1985 	if (checkout_target_fullpath(&fullpath, data, side->path) < 0)
1986 		return -1;
1987 
1988 	if ((conflict->name_collision || conflict->directoryfile) &&
1989 		(data->strategy & GIT_CHECKOUT_USE_OURS) == 0 &&
1990 		(data->strategy & GIT_CHECKOUT_USE_THEIRS) == 0) {
1991 
1992 		if (side == conflict->ours)
1993 			suffix = data->opts.our_label ? data->opts.our_label :
1994 				"ours";
1995 		else
1996 			suffix = data->opts.their_label ? data->opts.their_label :
1997 				"theirs";
1998 
1999 		if (checkout_path_suffixed(fullpath, suffix) < 0)
2000 			return -1;
2001 
2002 		hint_path = side->path;
2003 	}
2004 
2005 	if ((data->strategy & GIT_CHECKOUT_UPDATE_ONLY) != 0 &&
2006 		(error = checkout_safe_for_update_only(data, fullpath->ptr, side->mode)) <= 0)
2007 		return error;
2008 
2009 	if (!S_ISGITLINK(side->mode))
2010 		return checkout_write_content(data,
2011 					      &side->id, fullpath->ptr, hint_path, side->mode, &st);
2012 
2013 	return 0;
2014 }
2015 
checkout_write_entries(checkout_data * data,checkout_conflictdata * conflict)2016 static int checkout_write_entries(
2017 	checkout_data *data,
2018 	checkout_conflictdata *conflict)
2019 {
2020 	int error = 0;
2021 
2022 	if ((error = checkout_write_entry(data, conflict, conflict->ours)) >= 0)
2023 		error = checkout_write_entry(data, conflict, conflict->theirs);
2024 
2025 	return error;
2026 }
2027 
checkout_merge_path(git_buf * out,checkout_data * data,checkout_conflictdata * conflict,git_merge_file_result * result)2028 static int checkout_merge_path(
2029 	git_buf *out,
2030 	checkout_data *data,
2031 	checkout_conflictdata *conflict,
2032 	git_merge_file_result *result)
2033 {
2034 	const char *our_label_raw, *their_label_raw, *suffix;
2035 	int error = 0;
2036 
2037 	if ((error = git_buf_joinpath(out, data->opts.target_directory, result->path)) < 0 ||
2038 	    (error = git_path_validate_workdir_buf(data->repo, out)) < 0)
2039 		return error;
2040 
2041 	/* Most conflicts simply use the filename in the index */
2042 	if (!conflict->name_collision)
2043 		return 0;
2044 
2045 	/* Rename 2->1 conflicts need the branch name appended */
2046 	our_label_raw = data->opts.our_label ? data->opts.our_label : "ours";
2047 	their_label_raw = data->opts.their_label ? data->opts.their_label : "theirs";
2048 	suffix = strcmp(result->path, conflict->ours->path) == 0 ? our_label_raw : their_label_raw;
2049 
2050 	if ((error = checkout_path_suffixed(out, suffix)) < 0)
2051 		return error;
2052 
2053 	return 0;
2054 }
2055 
checkout_write_merge(checkout_data * data,checkout_conflictdata * conflict)2056 static int checkout_write_merge(
2057 	checkout_data *data,
2058 	checkout_conflictdata *conflict)
2059 {
2060 	git_buf our_label = GIT_BUF_INIT, their_label = GIT_BUF_INIT,
2061 		path_suffixed = GIT_BUF_INIT, path_workdir = GIT_BUF_INIT,
2062 		in_data = GIT_BUF_INIT, out_data = GIT_BUF_INIT;
2063 	git_merge_file_options opts = GIT_MERGE_FILE_OPTIONS_INIT;
2064 	git_merge_file_result result = {0};
2065 	git_filebuf output = GIT_FILEBUF_INIT;
2066 	git_filter_list *fl = NULL;
2067 	git_filter_options filter_opts = GIT_FILTER_OPTIONS_INIT;
2068 	int error = 0;
2069 
2070 	if (data->opts.checkout_strategy & GIT_CHECKOUT_CONFLICT_STYLE_DIFF3)
2071 		opts.flags |= GIT_MERGE_FILE_STYLE_DIFF3;
2072 
2073 	opts.ancestor_label = data->opts.ancestor_label ?
2074 		data->opts.ancestor_label : "ancestor";
2075 	opts.our_label = data->opts.our_label ?
2076 		data->opts.our_label : "ours";
2077 	opts.their_label = data->opts.their_label ?
2078 		data->opts.their_label : "theirs";
2079 
2080 	/* If all the paths are identical, decorate the diff3 file with the branch
2081 	 * names.  Otherwise, append branch_name:path.
2082 	 */
2083 	if (conflict->ours && conflict->theirs &&
2084 		strcmp(conflict->ours->path, conflict->theirs->path) != 0) {
2085 
2086 		if ((error = conflict_entry_name(
2087 			&our_label, opts.our_label, conflict->ours->path)) < 0 ||
2088 			(error = conflict_entry_name(
2089 			&their_label, opts.their_label, conflict->theirs->path)) < 0)
2090 			goto done;
2091 
2092 		opts.our_label = git_buf_cstr(&our_label);
2093 		opts.their_label = git_buf_cstr(&their_label);
2094 	}
2095 
2096 	if ((error = git_merge_file_from_index(&result, data->repo,
2097 		conflict->ancestor, conflict->ours, conflict->theirs, &opts)) < 0)
2098 		goto done;
2099 
2100 	if (result.path == NULL || result.mode == 0) {
2101 		git_error_set(GIT_ERROR_CHECKOUT, "could not merge contents of file");
2102 		error = GIT_ECONFLICT;
2103 		goto done;
2104 	}
2105 
2106 	if ((error = checkout_merge_path(&path_workdir, data, conflict, &result)) < 0)
2107 		goto done;
2108 
2109 	if ((data->strategy & GIT_CHECKOUT_UPDATE_ONLY) != 0 &&
2110 		(error = checkout_safe_for_update_only(data, git_buf_cstr(&path_workdir), result.mode)) <= 0)
2111 		goto done;
2112 
2113 	if (!data->opts.disable_filters) {
2114 		in_data.ptr = (char *)result.ptr;
2115 		in_data.size = result.len;
2116 
2117 		filter_opts.attr_session = &data->attr_session;
2118 		filter_opts.temp_buf = &data->tmp;
2119 
2120 		if ((error = git_filter_list__load_ext(
2121 				&fl, data->repo, NULL, git_buf_cstr(&path_workdir),
2122 				GIT_FILTER_TO_WORKTREE, &filter_opts)) < 0 ||
2123 			(error = git_filter_list__convert_buf(&out_data, fl, &in_data)) < 0)
2124 			goto done;
2125 	} else {
2126 		out_data.ptr = (char *)result.ptr;
2127 		out_data.size = result.len;
2128 	}
2129 
2130 	if ((error = mkpath2file(data, path_workdir.ptr, data->opts.dir_mode)) < 0 ||
2131 		(error = git_filebuf_open(&output, git_buf_cstr(&path_workdir), GIT_FILEBUF_DO_NOT_BUFFER, result.mode)) < 0 ||
2132 		(error = git_filebuf_write(&output, out_data.ptr, out_data.size)) < 0 ||
2133 		(error = git_filebuf_commit(&output)) < 0)
2134 		goto done;
2135 
2136 done:
2137 	git_filter_list_free(fl);
2138 
2139 	git_buf_dispose(&out_data);
2140 	git_buf_dispose(&our_label);
2141 	git_buf_dispose(&their_label);
2142 
2143 	git_merge_file_result_free(&result);
2144 	git_buf_dispose(&path_workdir);
2145 	git_buf_dispose(&path_suffixed);
2146 
2147 	return error;
2148 }
2149 
checkout_conflict_add(checkout_data * data,const git_index_entry * conflict)2150 static int checkout_conflict_add(
2151 	checkout_data *data,
2152 	const git_index_entry *conflict)
2153 {
2154 	int error = git_index_remove(data->index, conflict->path, 0);
2155 
2156 	if (error == GIT_ENOTFOUND)
2157 		git_error_clear();
2158 	else if (error < 0)
2159 		return error;
2160 
2161 	return git_index_add(data->index, conflict);
2162 }
2163 
checkout_conflict_update_index(checkout_data * data,checkout_conflictdata * conflict)2164 static int checkout_conflict_update_index(
2165 	checkout_data *data,
2166 	checkout_conflictdata *conflict)
2167 {
2168 	int error = 0;
2169 
2170 	if (conflict->ancestor)
2171 		error = checkout_conflict_add(data, conflict->ancestor);
2172 
2173 	if (!error && conflict->ours)
2174 		error = checkout_conflict_add(data, conflict->ours);
2175 
2176 	if (!error && conflict->theirs)
2177 		error = checkout_conflict_add(data, conflict->theirs);
2178 
2179 	return error;
2180 }
2181 
checkout_create_conflicts(checkout_data * data)2182 static int checkout_create_conflicts(checkout_data *data)
2183 {
2184 	checkout_conflictdata *conflict;
2185 	size_t i;
2186 	int error = 0;
2187 
2188 	git_vector_foreach(&data->update_conflicts, i, conflict) {
2189 
2190 		/* Both deleted: nothing to do */
2191 		if (conflict->ours == NULL && conflict->theirs == NULL)
2192 			error = 0;
2193 
2194 		else if ((data->strategy & GIT_CHECKOUT_USE_OURS) &&
2195 			conflict->ours)
2196 			error = checkout_write_entry(data, conflict, conflict->ours);
2197 		else if ((data->strategy & GIT_CHECKOUT_USE_THEIRS) &&
2198 			conflict->theirs)
2199 			error = checkout_write_entry(data, conflict, conflict->theirs);
2200 
2201 		/* Ignore the other side of name collisions. */
2202 		else if ((data->strategy & GIT_CHECKOUT_USE_OURS) &&
2203 			!conflict->ours && conflict->name_collision)
2204 			error = 0;
2205 		else if ((data->strategy & GIT_CHECKOUT_USE_THEIRS) &&
2206 			!conflict->theirs && conflict->name_collision)
2207 			error = 0;
2208 
2209 		/* For modify/delete, name collisions and d/f conflicts, write
2210 		 * the file (potentially with the name mangled.
2211 		 */
2212 		else if (conflict->ours != NULL && conflict->theirs == NULL)
2213 			error = checkout_write_entry(data, conflict, conflict->ours);
2214 		else if (conflict->ours == NULL && conflict->theirs != NULL)
2215 			error = checkout_write_entry(data, conflict, conflict->theirs);
2216 
2217 		/* Add/add conflicts and rename 1->2 conflicts, write the
2218 		 * ours/theirs sides (potentially name mangled).
2219 		 */
2220 		else if (conflict->one_to_two)
2221 			error = checkout_write_entries(data, conflict);
2222 
2223 		/* If all sides are links, write the ours side */
2224 		else if (S_ISLNK(conflict->ours->mode) &&
2225 			S_ISLNK(conflict->theirs->mode))
2226 			error = checkout_write_entry(data, conflict, conflict->ours);
2227 		/* Link/file conflicts, write the file side */
2228 		else if (S_ISLNK(conflict->ours->mode))
2229 			error = checkout_write_entry(data, conflict, conflict->theirs);
2230 		else if (S_ISLNK(conflict->theirs->mode))
2231 			error = checkout_write_entry(data, conflict, conflict->ours);
2232 
2233 		/* If any side is a gitlink, do nothing. */
2234 		else if (conflict->submodule)
2235 			error = 0;
2236 
2237 		/* If any side is binary, write the ours side */
2238 		else if (conflict->binary)
2239 			error = checkout_write_entry(data, conflict, conflict->ours);
2240 
2241 		else if (!error)
2242 			error = checkout_write_merge(data, conflict);
2243 
2244 		/* Update the index extensions (REUC and NAME) if we're checking
2245 		 * out a different index. (Otherwise just leave them there.)
2246 		 */
2247 		if (!error && (data->strategy & GIT_CHECKOUT_DONT_UPDATE_INDEX) == 0)
2248 			error = checkout_conflict_update_index(data, conflict);
2249 
2250 		if (error)
2251 			break;
2252 
2253 		data->completed_steps++;
2254 		report_progress(data,
2255 			conflict->ours ? conflict->ours->path :
2256 			(conflict->theirs ? conflict->theirs->path : conflict->ancestor->path));
2257 	}
2258 
2259 	return error;
2260 }
2261 
checkout_remove_conflicts(checkout_data * data)2262 static int checkout_remove_conflicts(checkout_data *data)
2263 {
2264 	const char *conflict;
2265 	size_t i;
2266 
2267 	git_vector_foreach(&data->remove_conflicts, i, conflict) {
2268 		if (git_index_conflict_remove(data->index, conflict) < 0)
2269 			return -1;
2270 
2271 		data->completed_steps++;
2272 	}
2273 
2274 	return 0;
2275 }
2276 
checkout_extensions_update_index(checkout_data * data)2277 static int checkout_extensions_update_index(checkout_data *data)
2278 {
2279 	const git_index_reuc_entry *reuc_entry;
2280 	const git_index_name_entry *name_entry;
2281 	size_t i;
2282 	int error = 0;
2283 
2284 	if ((data->strategy & GIT_CHECKOUT_UPDATE_ONLY) != 0)
2285 		return 0;
2286 
2287 	if (data->update_reuc) {
2288 		git_vector_foreach(data->update_reuc, i, reuc_entry) {
2289 			if ((error = git_index_reuc_add(data->index, reuc_entry->path,
2290 				reuc_entry->mode[0], &reuc_entry->oid[0],
2291 				reuc_entry->mode[1], &reuc_entry->oid[1],
2292 				reuc_entry->mode[2], &reuc_entry->oid[2])) < 0)
2293 				goto done;
2294 		}
2295 	}
2296 
2297 	if (data->update_names) {
2298 		git_vector_foreach(data->update_names, i, name_entry) {
2299 			if ((error = git_index_name_add(data->index, name_entry->ancestor,
2300 				name_entry->ours, name_entry->theirs)) < 0)
2301 				goto done;
2302 		}
2303 	}
2304 
2305 done:
2306 	return error;
2307 }
2308 
checkout_data_clear(checkout_data * data)2309 static void checkout_data_clear(checkout_data *data)
2310 {
2311 	if (data->opts_free_baseline) {
2312 		git_tree_free(data->opts.baseline);
2313 		data->opts.baseline = NULL;
2314 	}
2315 
2316 	git_vector_free(&data->removes);
2317 	git_pool_clear(&data->pool);
2318 
2319 	git_vector_free_deep(&data->remove_conflicts);
2320 	git_vector_free_deep(&data->update_conflicts);
2321 
2322 	git__free(data->pfx);
2323 	data->pfx = NULL;
2324 
2325 	git_buf_dispose(&data->target_path);
2326 	git_buf_dispose(&data->tmp);
2327 
2328 	git_index_free(data->index);
2329 	data->index = NULL;
2330 
2331 	git_strmap_free(data->mkdir_map);
2332 	data->mkdir_map = NULL;
2333 
2334 	git_attr_session__free(&data->attr_session);
2335 }
2336 
validate_target_directory(checkout_data * data)2337 static int validate_target_directory(checkout_data *data)
2338 {
2339 	int error;
2340 
2341 	if ((error = git_path_validate_workdir(data->repo, data->opts.target_directory)) < 0)
2342 		return error;
2343 
2344 	if (git_path_isdir(data->opts.target_directory))
2345 		return 0;
2346 
2347 	error = checkout_mkdir(data, data->opts.target_directory, NULL,
2348 	                       GIT_DIR_MODE, GIT_MKDIR_VERIFY_DIR);
2349 
2350 	return error;
2351 }
2352 
checkout_data_init(checkout_data * data,git_iterator * target,const git_checkout_options * proposed)2353 static int checkout_data_init(
2354 	checkout_data *data,
2355 	git_iterator *target,
2356 	const git_checkout_options *proposed)
2357 {
2358 	int error = 0;
2359 	git_repository *repo = git_iterator_owner(target);
2360 
2361 	memset(data, 0, sizeof(*data));
2362 
2363 	if (!repo) {
2364 		git_error_set(GIT_ERROR_CHECKOUT, "cannot checkout nothing");
2365 		return -1;
2366 	}
2367 
2368 	if ((!proposed || !proposed->target_directory) &&
2369 		(error = git_repository__ensure_not_bare(repo, "checkout")) < 0)
2370 		return error;
2371 
2372 	data->repo = repo;
2373 	data->target = target;
2374 
2375 	GIT_ERROR_CHECK_VERSION(
2376 		proposed, GIT_CHECKOUT_OPTIONS_VERSION, "git_checkout_options");
2377 
2378 	if (!proposed)
2379 		GIT_INIT_STRUCTURE(&data->opts, GIT_CHECKOUT_OPTIONS_VERSION);
2380 	else
2381 		memmove(&data->opts, proposed, sizeof(git_checkout_options));
2382 
2383 	if (!data->opts.target_directory)
2384 		data->opts.target_directory = git_repository_workdir(repo);
2385 	else if ((error = validate_target_directory(data)) < 0)
2386 		goto cleanup;
2387 
2388 	if ((error = git_repository_index(&data->index, data->repo)) < 0)
2389 		goto cleanup;
2390 
2391 	/* refresh config and index content unless NO_REFRESH is given */
2392 	if ((data->opts.checkout_strategy & GIT_CHECKOUT_NO_REFRESH) == 0) {
2393 		git_config *cfg;
2394 
2395 		if ((error = git_repository_config__weakptr(&cfg, repo)) < 0)
2396 			goto cleanup;
2397 
2398 		/* Reload the repository index (unless we're checking out the
2399 		 * index; then it has the changes we're trying to check out
2400 		 * and those should not be overwritten.)
2401 		 */
2402 		if (data->index != git_iterator_index(target)) {
2403 			if (data->opts.checkout_strategy & GIT_CHECKOUT_FORCE) {
2404 				/* When forcing, we can blindly re-read the index */
2405 				if ((error = git_index_read(data->index, false)) < 0)
2406 					goto cleanup;
2407 			} else {
2408 				/*
2409 				 * When not being forced, we need to check for unresolved
2410 				 * conflicts and unsaved changes in the index before
2411 				 * proceeding.
2412 				 */
2413 				if (git_index_has_conflicts(data->index)) {
2414 					error = GIT_ECONFLICT;
2415 					git_error_set(GIT_ERROR_CHECKOUT,
2416 						"unresolved conflicts exist in the index");
2417 					goto cleanup;
2418 				}
2419 
2420 				if ((error = git_index_read_safely(data->index)) < 0)
2421 					goto cleanup;
2422 			}
2423 
2424 			/* clean conflict data in the current index */
2425 			git_index_name_clear(data->index);
2426 			git_index_reuc_clear(data->index);
2427 		}
2428 	}
2429 
2430 	/* if you are forcing, allow all safe updates, plus recreate missing */
2431 	if ((data->opts.checkout_strategy & GIT_CHECKOUT_FORCE) != 0)
2432 		data->opts.checkout_strategy |= GIT_CHECKOUT_SAFE |
2433 			GIT_CHECKOUT_RECREATE_MISSING;
2434 
2435 	/* if the repository does not actually have an index file, then this
2436 	 * is an initial checkout (perhaps from clone), so we allow safe updates
2437 	 */
2438 	if (!data->index->on_disk &&
2439 		(data->opts.checkout_strategy & GIT_CHECKOUT_SAFE) != 0)
2440 		data->opts.checkout_strategy |= GIT_CHECKOUT_RECREATE_MISSING;
2441 
2442 	data->strategy = data->opts.checkout_strategy;
2443 
2444 	/* opts->disable_filters is false by default */
2445 
2446 	if (!data->opts.dir_mode)
2447 		data->opts.dir_mode = GIT_DIR_MODE;
2448 
2449 	if (!data->opts.file_open_flags)
2450 		data->opts.file_open_flags = O_CREAT | O_TRUNC | O_WRONLY;
2451 
2452 	data->pfx = git_pathspec_prefix(&data->opts.paths);
2453 
2454 	if ((error = git_repository__configmap_lookup(
2455 			 &data->can_symlink, repo, GIT_CONFIGMAP_SYMLINKS)) < 0)
2456 		goto cleanup;
2457 
2458 	if ((error = git_repository__configmap_lookup(
2459 			 &data->respect_filemode, repo, GIT_CONFIGMAP_FILEMODE)) < 0)
2460 		goto cleanup;
2461 
2462 	if (!data->opts.baseline && !data->opts.baseline_index) {
2463 		data->opts_free_baseline = true;
2464 		error = 0;
2465 
2466 		/* if we don't have an index, this is an initial checkout and
2467 		 * should be against an empty baseline
2468 		 */
2469 		if (data->index->on_disk)
2470 			error = checkout_lookup_head_tree(&data->opts.baseline, repo);
2471 
2472 		if (error == GIT_EUNBORNBRANCH) {
2473 			error = 0;
2474 			git_error_clear();
2475 		}
2476 
2477 		if (error < 0)
2478 			goto cleanup;
2479 	}
2480 
2481 	if ((data->opts.checkout_strategy &
2482 		(GIT_CHECKOUT_CONFLICT_STYLE_MERGE | GIT_CHECKOUT_CONFLICT_STYLE_DIFF3)) == 0) {
2483 		git_config_entry *conflict_style = NULL;
2484 		git_config *cfg = NULL;
2485 
2486 		if ((error = git_repository_config__weakptr(&cfg, repo)) < 0 ||
2487 			(error = git_config_get_entry(&conflict_style, cfg, "merge.conflictstyle")) < 0 ||
2488 			error == GIT_ENOTFOUND)
2489 			;
2490 		else if (error)
2491 			goto cleanup;
2492 		else if (strcmp(conflict_style->value, "merge") == 0)
2493 			data->opts.checkout_strategy |= GIT_CHECKOUT_CONFLICT_STYLE_MERGE;
2494 		else if (strcmp(conflict_style->value, "diff3") == 0)
2495 			data->opts.checkout_strategy |= GIT_CHECKOUT_CONFLICT_STYLE_DIFF3;
2496 		else {
2497 			git_error_set(GIT_ERROR_CHECKOUT, "unknown style '%s' given for 'merge.conflictstyle'",
2498 				conflict_style->value);
2499 			error = -1;
2500 			git_config_entry_free(conflict_style);
2501 			goto cleanup;
2502 		}
2503 		git_config_entry_free(conflict_style);
2504 	}
2505 
2506 	if ((error = git_pool_init(&data->pool, 1)) < 0 ||
2507 	    (error = git_vector_init(&data->removes, 0, git__strcmp_cb)) < 0 ||
2508 	    (error = git_vector_init(&data->remove_conflicts, 0, NULL)) < 0 ||
2509 	    (error = git_vector_init(&data->update_conflicts, 0, NULL)) < 0 ||
2510 	    (error = git_buf_puts(&data->target_path, data->opts.target_directory)) < 0 ||
2511 	    (error = git_path_to_dir(&data->target_path)) < 0 ||
2512 	    (error = git_strmap_new(&data->mkdir_map)) < 0)
2513 		goto cleanup;
2514 
2515 	data->target_len = git_buf_len(&data->target_path);
2516 
2517 	git_attr_session__init(&data->attr_session, data->repo);
2518 
2519 cleanup:
2520 	if (error < 0)
2521 		checkout_data_clear(data);
2522 
2523 	return error;
2524 }
2525 
2526 #define CHECKOUT_INDEX_DONT_WRITE_MASK \
2527 	(GIT_CHECKOUT_DONT_UPDATE_INDEX | GIT_CHECKOUT_DONT_WRITE_INDEX)
2528 
setup_pathspecs(git_iterator_options * iter_opts,const git_checkout_options * checkout_opts)2529 GIT_INLINE(void) setup_pathspecs(
2530 	git_iterator_options *iter_opts,
2531 	const git_checkout_options *checkout_opts)
2532 {
2533 	if (checkout_opts &&
2534 		(checkout_opts->checkout_strategy & GIT_CHECKOUT_DISABLE_PATHSPEC_MATCH)) {
2535 		iter_opts->pathlist.count = checkout_opts->paths.count;
2536 		iter_opts->pathlist.strings = checkout_opts->paths.strings;
2537 	}
2538 }
2539 
git_checkout_iterator(git_iterator * target,git_index * index,const git_checkout_options * opts)2540 int git_checkout_iterator(
2541 	git_iterator *target,
2542 	git_index *index,
2543 	const git_checkout_options *opts)
2544 {
2545 	int error = 0;
2546 	git_iterator *baseline = NULL, *workdir = NULL;
2547 	git_iterator_options baseline_opts = GIT_ITERATOR_OPTIONS_INIT,
2548 		workdir_opts = GIT_ITERATOR_OPTIONS_INIT;
2549 	checkout_data data = {0};
2550 	git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT;
2551 	uint32_t *actions = NULL;
2552 	size_t *counts = NULL;
2553 
2554 	/* initialize structures and options */
2555 	error = checkout_data_init(&data, target, opts);
2556 	if (error < 0)
2557 		return error;
2558 
2559 	diff_opts.flags =
2560 		GIT_DIFF_INCLUDE_UNMODIFIED |
2561 		GIT_DIFF_INCLUDE_UNREADABLE |
2562 		GIT_DIFF_INCLUDE_UNTRACKED |
2563 		GIT_DIFF_RECURSE_UNTRACKED_DIRS | /* needed to match baseline */
2564 		GIT_DIFF_INCLUDE_IGNORED |
2565 		GIT_DIFF_INCLUDE_TYPECHANGE |
2566 		GIT_DIFF_INCLUDE_TYPECHANGE_TREES |
2567 		GIT_DIFF_SKIP_BINARY_CHECK |
2568 		GIT_DIFF_INCLUDE_CASECHANGE;
2569 	if (data.opts.checkout_strategy & GIT_CHECKOUT_DISABLE_PATHSPEC_MATCH)
2570 		diff_opts.flags |= GIT_DIFF_DISABLE_PATHSPEC_MATCH;
2571 	if (data.opts.paths.count > 0)
2572 		diff_opts.pathspec = data.opts.paths;
2573 
2574 	/* set up iterators */
2575 
2576 	workdir_opts.flags = git_iterator_ignore_case(target) ?
2577 		GIT_ITERATOR_IGNORE_CASE : GIT_ITERATOR_DONT_IGNORE_CASE;
2578 	workdir_opts.flags |= GIT_ITERATOR_DONT_AUTOEXPAND;
2579 	workdir_opts.start = data.pfx;
2580 	workdir_opts.end = data.pfx;
2581 
2582 	setup_pathspecs(&workdir_opts, opts);
2583 
2584 	if ((error = git_iterator_reset_range(target, data.pfx, data.pfx)) < 0 ||
2585 		(error = git_iterator_for_workdir_ext(
2586 			&workdir, data.repo, data.opts.target_directory, index, NULL,
2587 			&workdir_opts)) < 0)
2588 		goto cleanup;
2589 
2590 	baseline_opts.flags = git_iterator_ignore_case(target) ?
2591 		GIT_ITERATOR_IGNORE_CASE : GIT_ITERATOR_DONT_IGNORE_CASE;
2592 	baseline_opts.start = data.pfx;
2593 	baseline_opts.end = data.pfx;
2594 
2595 	setup_pathspecs(&baseline_opts, opts);
2596 
2597 	if (data.opts.baseline_index) {
2598 		if ((error = git_iterator_for_index(
2599 				&baseline, git_index_owner(data.opts.baseline_index),
2600 				data.opts.baseline_index, &baseline_opts)) < 0)
2601 			goto cleanup;
2602 	} else {
2603 		if ((error = git_iterator_for_tree(
2604 				&baseline, data.opts.baseline, &baseline_opts)) < 0)
2605 			goto cleanup;
2606 	}
2607 
2608 	/* Should not have case insensitivity mismatch */
2609 	GIT_ASSERT(git_iterator_ignore_case(workdir) == git_iterator_ignore_case(baseline));
2610 
2611 	/* Generate baseline-to-target diff which will include an entry for
2612 	 * every possible update that might need to be made.
2613 	 */
2614 	if ((error = git_diff__from_iterators(
2615 			&data.diff, data.repo, baseline, target, &diff_opts)) < 0)
2616 		goto cleanup;
2617 
2618 	/* Loop through diff (and working directory iterator) building a list of
2619 	 * actions to be taken, plus look for conflicts and send notifications,
2620 	 * then loop through conflicts.
2621 	 */
2622 	if ((error = checkout_get_actions(&actions, &counts, &data, workdir)) != 0)
2623 		goto cleanup;
2624 
2625 	data.total_steps = counts[CHECKOUT_ACTION__REMOVE] +
2626 		counts[CHECKOUT_ACTION__REMOVE_CONFLICT] +
2627 		counts[CHECKOUT_ACTION__UPDATE_BLOB] +
2628 		counts[CHECKOUT_ACTION__UPDATE_SUBMODULE] +
2629 		counts[CHECKOUT_ACTION__UPDATE_CONFLICT];
2630 
2631 	report_progress(&data, NULL); /* establish 0 baseline */
2632 
2633 	/* To deal with some order dependencies, perform remaining checkout
2634 	 * in three passes: removes, then update blobs, then update submodules.
2635 	 */
2636 	if (counts[CHECKOUT_ACTION__REMOVE] > 0 &&
2637 		(error = checkout_remove_the_old(actions, &data)) < 0)
2638 		goto cleanup;
2639 
2640 	if (counts[CHECKOUT_ACTION__REMOVE_CONFLICT] > 0 &&
2641 		(error = checkout_remove_conflicts(&data)) < 0)
2642 		goto cleanup;
2643 
2644 	if (counts[CHECKOUT_ACTION__UPDATE_BLOB] > 0 &&
2645 		(error = checkout_create_the_new(actions, &data)) < 0)
2646 		goto cleanup;
2647 
2648 	if (counts[CHECKOUT_ACTION__UPDATE_SUBMODULE] > 0 &&
2649 		(error = checkout_create_submodules(actions, &data)) < 0)
2650 		goto cleanup;
2651 
2652 	if (counts[CHECKOUT_ACTION__UPDATE_CONFLICT] > 0 &&
2653 		(error = checkout_create_conflicts(&data)) < 0)
2654 		goto cleanup;
2655 
2656 	if (data.index != git_iterator_index(target) &&
2657 		(error = checkout_extensions_update_index(&data)) < 0)
2658 		goto cleanup;
2659 
2660 	GIT_ASSERT(data.completed_steps == data.total_steps);
2661 
2662 	if (data.opts.perfdata_cb)
2663 		data.opts.perfdata_cb(&data.perfdata, data.opts.perfdata_payload);
2664 
2665 cleanup:
2666 	if (!error && data.index != NULL &&
2667 		(data.strategy & CHECKOUT_INDEX_DONT_WRITE_MASK) == 0)
2668 		error = git_index_write(data.index);
2669 
2670 	git_diff_free(data.diff);
2671 	git_iterator_free(workdir);
2672 	git_iterator_free(baseline);
2673 	git__free(actions);
2674 	git__free(counts);
2675 	checkout_data_clear(&data);
2676 
2677 	return error;
2678 }
2679 
git_checkout_index(git_repository * repo,git_index * index,const git_checkout_options * opts)2680 int git_checkout_index(
2681 	git_repository *repo,
2682 	git_index *index,
2683 	const git_checkout_options *opts)
2684 {
2685 	git_iterator_options iter_opts = GIT_ITERATOR_OPTIONS_INIT;
2686 	int error, owned = 0;
2687 	git_iterator *index_i;
2688 
2689 	if (!index && !repo) {
2690 		git_error_set(GIT_ERROR_CHECKOUT,
2691 			"must provide either repository or index to checkout");
2692 		return -1;
2693 	}
2694 
2695 	if (index && repo &&
2696 		git_index_owner(index) &&
2697 		git_index_owner(index) != repo) {
2698 		git_error_set(GIT_ERROR_CHECKOUT,
2699 			"index to checkout does not match repository");
2700 		return -1;
2701 	} else if(index && repo && !git_index_owner(index)) {
2702 		GIT_REFCOUNT_OWN(index, repo);
2703 		owned = 1;
2704 	}
2705 
2706 	if (!repo)
2707 		repo = git_index_owner(index);
2708 
2709 	if (!index && (error = git_repository_index__weakptr(&index, repo)) < 0)
2710 		return error;
2711 	GIT_REFCOUNT_INC(index);
2712 
2713 	setup_pathspecs(&iter_opts, opts);
2714 
2715 	if (!(error = git_iterator_for_index(&index_i, repo, index, &iter_opts)))
2716 		error = git_checkout_iterator(index_i, index, opts);
2717 
2718 	if (owned)
2719 		GIT_REFCOUNT_OWN(index, NULL);
2720 
2721 	git_iterator_free(index_i);
2722 	git_index_free(index);
2723 
2724 	return error;
2725 }
2726 
git_checkout_tree(git_repository * repo,const git_object * treeish,const git_checkout_options * opts)2727 int git_checkout_tree(
2728 	git_repository *repo,
2729 	const git_object *treeish,
2730 	const git_checkout_options *opts)
2731 {
2732 	int error;
2733 	git_index *index;
2734 	git_tree *tree = NULL;
2735 	git_iterator *tree_i = NULL;
2736 	git_iterator_options iter_opts = GIT_ITERATOR_OPTIONS_INIT;
2737 
2738 	if (!treeish && !repo) {
2739 		git_error_set(GIT_ERROR_CHECKOUT,
2740 			"must provide either repository or tree to checkout");
2741 		return -1;
2742 	}
2743 	if (treeish && repo && git_object_owner(treeish) != repo) {
2744 		git_error_set(GIT_ERROR_CHECKOUT,
2745 			"object to checkout does not match repository");
2746 		return -1;
2747 	}
2748 
2749 	if (!repo)
2750 		repo = git_object_owner(treeish);
2751 
2752 	if (treeish) {
2753 		if (git_object_peel((git_object **)&tree, treeish, GIT_OBJECT_TREE) < 0) {
2754 			git_error_set(
2755 				GIT_ERROR_CHECKOUT, "provided object cannot be peeled to a tree");
2756 			return -1;
2757 		}
2758 	}
2759 	else {
2760 		if ((error = checkout_lookup_head_tree(&tree, repo)) < 0) {
2761 			if (error != GIT_EUNBORNBRANCH)
2762 				git_error_set(
2763 					GIT_ERROR_CHECKOUT,
2764 					"HEAD could not be peeled to a tree and no treeish given");
2765 			return error;
2766 		}
2767 	}
2768 
2769 	if ((error = git_repository_index(&index, repo)) < 0)
2770 		return error;
2771 
2772 	setup_pathspecs(&iter_opts, opts);
2773 
2774 	if (!(error = git_iterator_for_tree(&tree_i, tree, &iter_opts)))
2775 		error = git_checkout_iterator(tree_i, index, opts);
2776 
2777 	git_iterator_free(tree_i);
2778 	git_index_free(index);
2779 	git_tree_free(tree);
2780 
2781 	return error;
2782 }
2783 
git_checkout_head(git_repository * repo,const git_checkout_options * opts)2784 int git_checkout_head(
2785 	git_repository *repo,
2786 	const git_checkout_options *opts)
2787 {
2788 	GIT_ASSERT_ARG(repo);
2789 
2790 	return git_checkout_tree(repo, NULL, opts);
2791 }
2792 
git_checkout_options_init(git_checkout_options * opts,unsigned int version)2793 int git_checkout_options_init(git_checkout_options *opts, unsigned int version)
2794 {
2795 	GIT_INIT_STRUCTURE_FROM_TEMPLATE(
2796 		opts, version, git_checkout_options, GIT_CHECKOUT_OPTIONS_INIT);
2797 	return 0;
2798 }
2799 
2800 #ifndef GIT_DEPRECATE_HARD
git_checkout_init_options(git_checkout_options * opts,unsigned int version)2801 int git_checkout_init_options(git_checkout_options *opts, unsigned int version)
2802 {
2803 	return git_checkout_options_init(opts, version);
2804 }
2805 #endif
2806