1 /*
2  * "git difftool" builtin command
3  *
4  * This is a wrapper around the GIT_EXTERNAL_DIFF-compatible
5  * git-difftool--helper script.
6  *
7  * This script exports GIT_EXTERNAL_DIFF and GIT_PAGER for use by git.
8  * The GIT_DIFF* variables are exported for use by git-difftool--helper.
9  *
10  * Any arguments that are unknown to this script are forwarded to 'git diff'.
11  *
12  * Copyright (C) 2016 Johannes Schindelin
13  */
14 #define USE_THE_INDEX_COMPATIBILITY_MACROS
15 #include "cache.h"
16 #include "config.h"
17 #include "builtin.h"
18 #include "run-command.h"
19 #include "exec-cmd.h"
20 #include "parse-options.h"
21 #include "strvec.h"
22 #include "strbuf.h"
23 #include "lockfile.h"
24 #include "object-store.h"
25 #include "dir.h"
26 #include "entry.h"
27 
28 static int trust_exit_code;
29 
30 static const char *const builtin_difftool_usage[] = {
31 	N_("git difftool [<options>] [<commit> [<commit>]] [--] [<path>...]"),
32 	NULL
33 };
34 
difftool_config(const char * var,const char * value,void * cb)35 static int difftool_config(const char *var, const char *value, void *cb)
36 {
37 	if (!strcmp(var, "difftool.trustexitcode")) {
38 		trust_exit_code = git_config_bool(var, value);
39 		return 0;
40 	}
41 
42 	return git_default_config(var, value, cb);
43 }
44 
print_tool_help(void)45 static int print_tool_help(void)
46 {
47 	const char *argv[] = { "mergetool", "--tool-help=diff", NULL };
48 	return run_command_v_opt(argv, RUN_GIT_CMD);
49 }
50 
parse_index_info(char * p,int * mode1,int * mode2,struct object_id * oid1,struct object_id * oid2,char * status)51 static int parse_index_info(char *p, int *mode1, int *mode2,
52 			    struct object_id *oid1, struct object_id *oid2,
53 			    char *status)
54 {
55 	if (*p != ':')
56 		return error("expected ':', got '%c'", *p);
57 	*mode1 = (int)strtol(p + 1, &p, 8);
58 	if (*p != ' ')
59 		return error("expected ' ', got '%c'", *p);
60 	*mode2 = (int)strtol(p + 1, &p, 8);
61 	if (*p != ' ')
62 		return error("expected ' ', got '%c'", *p);
63 	if (parse_oid_hex(++p, oid1, (const char **)&p))
64 		return error("expected object ID, got '%s'", p);
65 	if (*p != ' ')
66 		return error("expected ' ', got '%c'", *p);
67 	if (parse_oid_hex(++p, oid2, (const char **)&p))
68 		return error("expected object ID, got '%s'", p);
69 	if (*p != ' ')
70 		return error("expected ' ', got '%c'", *p);
71 	*status = *++p;
72 	if (!*status)
73 		return error("missing status");
74 	if (p[1] && !isdigit(p[1]))
75 		return error("unexpected trailer: '%s'", p + 1);
76 	return 0;
77 }
78 
79 /*
80  * Remove any trailing slash from $workdir
81  * before starting to avoid double slashes in symlink targets.
82  */
add_path(struct strbuf * buf,size_t base_len,const char * path)83 static void add_path(struct strbuf *buf, size_t base_len, const char *path)
84 {
85 	strbuf_setlen(buf, base_len);
86 	if (buf->len && buf->buf[buf->len - 1] != '/')
87 		strbuf_addch(buf, '/');
88 	strbuf_addstr(buf, path);
89 }
90 
91 /*
92  * Determine whether we can simply reuse the file in the worktree.
93  */
use_wt_file(const char * workdir,const char * name,struct object_id * oid)94 static int use_wt_file(const char *workdir, const char *name,
95 		       struct object_id *oid)
96 {
97 	struct strbuf buf = STRBUF_INIT;
98 	struct stat st;
99 	int use = 0;
100 
101 	strbuf_addstr(&buf, workdir);
102 	add_path(&buf, buf.len, name);
103 
104 	if (!lstat(buf.buf, &st) && !S_ISLNK(st.st_mode)) {
105 		struct object_id wt_oid;
106 		int fd = open(buf.buf, O_RDONLY);
107 
108 		if (fd >= 0 &&
109 		    !index_fd(&the_index, &wt_oid, fd, &st, OBJ_BLOB, name, 0)) {
110 			if (is_null_oid(oid)) {
111 				oidcpy(oid, &wt_oid);
112 				use = 1;
113 			} else if (oideq(oid, &wt_oid))
114 				use = 1;
115 		}
116 	}
117 
118 	strbuf_release(&buf);
119 
120 	return use;
121 }
122 
123 struct working_tree_entry {
124 	struct hashmap_entry entry;
125 	char path[FLEX_ARRAY];
126 };
127 
working_tree_entry_cmp(const void * unused_cmp_data,const struct hashmap_entry * eptr,const struct hashmap_entry * entry_or_key,const void * unused_keydata)128 static int working_tree_entry_cmp(const void *unused_cmp_data,
129 				  const struct hashmap_entry *eptr,
130 				  const struct hashmap_entry *entry_or_key,
131 				  const void *unused_keydata)
132 {
133 	const struct working_tree_entry *a, *b;
134 
135 	a = container_of(eptr, const struct working_tree_entry, entry);
136 	b = container_of(entry_or_key, const struct working_tree_entry, entry);
137 
138 	return strcmp(a->path, b->path);
139 }
140 
141 /*
142  * The `left` and `right` entries hold paths for the symlinks hashmap,
143  * and a SHA-1 surrounded by brief text for submodules.
144  */
145 struct pair_entry {
146 	struct hashmap_entry entry;
147 	char left[PATH_MAX], right[PATH_MAX];
148 	const char path[FLEX_ARRAY];
149 };
150 
pair_cmp(const void * unused_cmp_data,const struct hashmap_entry * eptr,const struct hashmap_entry * entry_or_key,const void * unused_keydata)151 static int pair_cmp(const void *unused_cmp_data,
152 		    const struct hashmap_entry *eptr,
153 		    const struct hashmap_entry *entry_or_key,
154 		    const void *unused_keydata)
155 {
156 	const struct pair_entry *a, *b;
157 
158 	a = container_of(eptr, const struct pair_entry, entry);
159 	b = container_of(entry_or_key, const struct pair_entry, entry);
160 
161 	return strcmp(a->path, b->path);
162 }
163 
add_left_or_right(struct hashmap * map,const char * path,const char * content,int is_right)164 static void add_left_or_right(struct hashmap *map, const char *path,
165 			      const char *content, int is_right)
166 {
167 	struct pair_entry *e, *existing;
168 
169 	FLEX_ALLOC_STR(e, path, path);
170 	hashmap_entry_init(&e->entry, strhash(path));
171 	existing = hashmap_get_entry(map, e, entry, NULL);
172 	if (existing) {
173 		free(e);
174 		e = existing;
175 	} else {
176 		e->left[0] = e->right[0] = '\0';
177 		hashmap_add(map, &e->entry);
178 	}
179 	strlcpy(is_right ? e->right : e->left, content, PATH_MAX);
180 }
181 
182 struct path_entry {
183 	struct hashmap_entry entry;
184 	char path[FLEX_ARRAY];
185 };
186 
path_entry_cmp(const void * unused_cmp_data,const struct hashmap_entry * eptr,const struct hashmap_entry * entry_or_key,const void * key)187 static int path_entry_cmp(const void *unused_cmp_data,
188 			  const struct hashmap_entry *eptr,
189 			  const struct hashmap_entry *entry_or_key,
190 			  const void *key)
191 {
192 	const struct path_entry *a, *b;
193 
194 	a = container_of(eptr, const struct path_entry, entry);
195 	b = container_of(entry_or_key, const struct path_entry, entry);
196 
197 	return strcmp(a->path, key ? key : b->path);
198 }
199 
changed_files(struct hashmap * result,const char * index_path,const char * workdir)200 static void changed_files(struct hashmap *result, const char *index_path,
201 			  const char *workdir)
202 {
203 	struct child_process update_index = CHILD_PROCESS_INIT;
204 	struct child_process diff_files = CHILD_PROCESS_INIT;
205 	struct strbuf index_env = STRBUF_INIT, buf = STRBUF_INIT;
206 	const char *git_dir = absolute_path(get_git_dir()), *env[] = {
207 		NULL, NULL
208 	};
209 	FILE *fp;
210 
211 	strbuf_addf(&index_env, "GIT_INDEX_FILE=%s", index_path);
212 	env[0] = index_env.buf;
213 
214 	strvec_pushl(&update_index.args,
215 		     "--git-dir", git_dir, "--work-tree", workdir,
216 		     "update-index", "--really-refresh", "-q",
217 		     "--unmerged", NULL);
218 	update_index.no_stdin = 1;
219 	update_index.no_stdout = 1;
220 	update_index.no_stderr = 1;
221 	update_index.git_cmd = 1;
222 	update_index.use_shell = 0;
223 	update_index.clean_on_exit = 1;
224 	update_index.dir = workdir;
225 	update_index.env = env;
226 	/* Ignore any errors of update-index */
227 	run_command(&update_index);
228 
229 	strvec_pushl(&diff_files.args,
230 		     "--git-dir", git_dir, "--work-tree", workdir,
231 		     "diff-files", "--name-only", "-z", NULL);
232 	diff_files.no_stdin = 1;
233 	diff_files.git_cmd = 1;
234 	diff_files.use_shell = 0;
235 	diff_files.clean_on_exit = 1;
236 	diff_files.out = -1;
237 	diff_files.dir = workdir;
238 	diff_files.env = env;
239 	if (start_command(&diff_files))
240 		die("could not obtain raw diff");
241 	fp = xfdopen(diff_files.out, "r");
242 	while (!strbuf_getline_nul(&buf, fp)) {
243 		struct path_entry *entry;
244 		FLEX_ALLOC_STR(entry, path, buf.buf);
245 		hashmap_entry_init(&entry->entry, strhash(buf.buf));
246 		hashmap_add(result, &entry->entry);
247 	}
248 	fclose(fp);
249 	if (finish_command(&diff_files))
250 		die("diff-files did not exit properly");
251 	strbuf_release(&index_env);
252 	strbuf_release(&buf);
253 }
254 
ensure_leading_directories(char * path)255 static int ensure_leading_directories(char *path)
256 {
257 	switch (safe_create_leading_directories(path)) {
258 		case SCLD_OK:
259 		case SCLD_EXISTS:
260 			return 0;
261 		default:
262 			return error(_("could not create leading directories "
263 				       "of '%s'"), path);
264 	}
265 }
266 
267 /*
268  * Unconditional writing of a plain regular file is what
269  * "git difftool --dir-diff" wants to do for symlinks.  We are preparing two
270  * temporary directories to be fed to a Git-unaware tool that knows how to
271  * show a diff of two directories (e.g. "diff -r A B").
272  *
273  * Because the tool is Git-unaware, if a symbolic link appears in either of
274  * these temporary directories, it will try to dereference and show the
275  * difference of the target of the symbolic link, which is not what we want,
276  * as the goal of the dir-diff mode is to produce an output that is logically
277  * equivalent to what "git diff" produces.
278  *
279  * Most importantly, we want to get textual comparison of the result of the
280  * readlink(2).  get_symlink() provides that---it returns the contents of
281  * the symlink that gets written to a regular file to force the external tool
282  * to compare the readlink(2) result as text, even on a filesystem that is
283  * capable of doing a symbolic link.
284  */
get_symlink(const struct object_id * oid,const char * path)285 static char *get_symlink(const struct object_id *oid, const char *path)
286 {
287 	char *data;
288 	if (is_null_oid(oid)) {
289 		/* The symlink is unknown to Git so read from the filesystem */
290 		struct strbuf link = STRBUF_INIT;
291 		if (has_symlinks) {
292 			if (strbuf_readlink(&link, path, strlen(path)))
293 				die(_("could not read symlink %s"), path);
294 		} else if (strbuf_read_file(&link, path, 128))
295 			die(_("could not read symlink file %s"), path);
296 
297 		data = strbuf_detach(&link, NULL);
298 	} else {
299 		enum object_type type;
300 		unsigned long size;
301 		data = read_object_file(oid, &type, &size);
302 		if (!data)
303 			die(_("could not read object %s for symlink %s"),
304 				oid_to_hex(oid), path);
305 	}
306 
307 	return data;
308 }
309 
checkout_path(unsigned mode,struct object_id * oid,const char * path,const struct checkout * state)310 static int checkout_path(unsigned mode, struct object_id *oid,
311 			 const char *path, const struct checkout *state)
312 {
313 	struct cache_entry *ce;
314 	int ret;
315 
316 	ce = make_transient_cache_entry(mode, oid, path, 0, NULL);
317 	ret = checkout_entry(ce, state, NULL, NULL);
318 
319 	discard_cache_entry(ce);
320 	return ret;
321 }
322 
write_file_in_directory(struct strbuf * dir,size_t dir_len,const char * path,const char * content)323 static void write_file_in_directory(struct strbuf *dir, size_t dir_len,
324 			const char *path, const char *content)
325 {
326 	add_path(dir, dir_len, path);
327 	ensure_leading_directories(dir->buf);
328 	unlink(dir->buf);
329 	write_file(dir->buf, "%s", content);
330 }
331 
332 /* Write the file contents for the left and right sides of the difftool
333  * dir-diff representation for submodules and symlinks. Symlinks and submodules
334  * are written as regular text files so that external diff tools can diff them
335  * as text files, resulting in behavior that is analogous to to what "git diff"
336  * displays for symlink and submodule diffs.
337  */
write_standin_files(struct pair_entry * entry,struct strbuf * ldir,size_t ldir_len,struct strbuf * rdir,size_t rdir_len)338 static void write_standin_files(struct pair_entry *entry,
339 			struct strbuf *ldir, size_t ldir_len,
340 			struct strbuf *rdir, size_t rdir_len)
341 {
342 	if (*entry->left)
343 		write_file_in_directory(ldir, ldir_len, entry->path, entry->left);
344 	if (*entry->right)
345 		write_file_in_directory(rdir, rdir_len, entry->path, entry->right);
346 }
347 
run_dir_diff(const char * extcmd,int symlinks,const char * prefix,struct child_process * child)348 static int run_dir_diff(const char *extcmd, int symlinks, const char *prefix,
349 			struct child_process *child)
350 {
351 	struct strbuf info = STRBUF_INIT, lpath = STRBUF_INIT;
352 	struct strbuf rpath = STRBUF_INIT, buf = STRBUF_INIT;
353 	struct strbuf ldir = STRBUF_INIT, rdir = STRBUF_INIT;
354 	struct strbuf wtdir = STRBUF_INIT;
355 	struct strbuf tmpdir = STRBUF_INIT;
356 	char *lbase_dir = NULL, *rbase_dir = NULL;
357 	size_t ldir_len, rdir_len, wtdir_len;
358 	const char *workdir, *tmp;
359 	int ret = 0, i;
360 	FILE *fp = NULL;
361 	struct hashmap working_tree_dups = HASHMAP_INIT(working_tree_entry_cmp,
362 							NULL);
363 	struct hashmap submodules = HASHMAP_INIT(pair_cmp, NULL);
364 	struct hashmap symlinks2 = HASHMAP_INIT(pair_cmp, NULL);
365 	struct hashmap_iter iter;
366 	struct pair_entry *entry;
367 	struct index_state wtindex;
368 	struct checkout lstate, rstate;
369 	int flags = RUN_GIT_CMD, err = 0;
370 	const char *helper_argv[] = { "difftool--helper", NULL, NULL, NULL };
371 	struct hashmap wt_modified, tmp_modified;
372 	int indices_loaded = 0;
373 
374 	workdir = get_git_work_tree();
375 
376 	/* Setup temp directories */
377 	tmp = getenv("TMPDIR");
378 	strbuf_add_absolute_path(&tmpdir, tmp ? tmp : "/tmp");
379 	strbuf_trim_trailing_dir_sep(&tmpdir);
380 	strbuf_addstr(&tmpdir, "/git-difftool.XXXXXX");
381 	if (!mkdtemp(tmpdir.buf)) {
382 		ret = error("could not create '%s'", tmpdir.buf);
383 		goto finish;
384 	}
385 	strbuf_addf(&ldir, "%s/left/", tmpdir.buf);
386 	strbuf_addf(&rdir, "%s/right/", tmpdir.buf);
387 	strbuf_addstr(&wtdir, workdir);
388 	if (!wtdir.len || !is_dir_sep(wtdir.buf[wtdir.len - 1]))
389 		strbuf_addch(&wtdir, '/');
390 	mkdir(ldir.buf, 0700);
391 	mkdir(rdir.buf, 0700);
392 
393 	memset(&wtindex, 0, sizeof(wtindex));
394 
395 	memset(&lstate, 0, sizeof(lstate));
396 	lstate.base_dir = lbase_dir = xstrdup(ldir.buf);
397 	lstate.base_dir_len = ldir.len;
398 	lstate.force = 1;
399 	memset(&rstate, 0, sizeof(rstate));
400 	rstate.base_dir = rbase_dir = xstrdup(rdir.buf);
401 	rstate.base_dir_len = rdir.len;
402 	rstate.force = 1;
403 
404 	ldir_len = ldir.len;
405 	rdir_len = rdir.len;
406 	wtdir_len = wtdir.len;
407 
408 	child->no_stdin = 1;
409 	child->git_cmd = 1;
410 	child->use_shell = 0;
411 	child->clean_on_exit = 1;
412 	child->dir = prefix;
413 	child->out = -1;
414 	if (start_command(child))
415 		die("could not obtain raw diff");
416 	fp = xfdopen(child->out, "r");
417 
418 	/* Build index info for left and right sides of the diff */
419 	i = 0;
420 	while (!strbuf_getline_nul(&info, fp)) {
421 		int lmode, rmode;
422 		struct object_id loid, roid;
423 		char status;
424 		const char *src_path, *dst_path;
425 
426 		if (starts_with(info.buf, "::"))
427 			die(N_("combined diff formats ('-c' and '--cc') are "
428 			       "not supported in\n"
429 			       "directory diff mode ('-d' and '--dir-diff')."));
430 
431 		if (parse_index_info(info.buf, &lmode, &rmode, &loid, &roid,
432 				     &status))
433 			break;
434 		if (strbuf_getline_nul(&lpath, fp))
435 			break;
436 		src_path = lpath.buf;
437 
438 		i++;
439 		if (status != 'C' && status != 'R') {
440 			dst_path = src_path;
441 		} else {
442 			if (strbuf_getline_nul(&rpath, fp))
443 				break;
444 			dst_path = rpath.buf;
445 		}
446 
447 		if (S_ISGITLINK(lmode) || S_ISGITLINK(rmode)) {
448 			strbuf_reset(&buf);
449 			strbuf_addf(&buf, "Subproject commit %s",
450 				    oid_to_hex(&loid));
451 			add_left_or_right(&submodules, src_path, buf.buf, 0);
452 			strbuf_reset(&buf);
453 			strbuf_addf(&buf, "Subproject commit %s",
454 				    oid_to_hex(&roid));
455 			if (oideq(&loid, &roid))
456 				strbuf_addstr(&buf, "-dirty");
457 			add_left_or_right(&submodules, dst_path, buf.buf, 1);
458 			continue;
459 		}
460 
461 		if (S_ISLNK(lmode)) {
462 			char *content = get_symlink(&loid, src_path);
463 			add_left_or_right(&symlinks2, src_path, content, 0);
464 			free(content);
465 		}
466 
467 		if (S_ISLNK(rmode)) {
468 			char *content = get_symlink(&roid, dst_path);
469 			add_left_or_right(&symlinks2, dst_path, content, 1);
470 			free(content);
471 		}
472 
473 		if (lmode && status != 'C') {
474 			if (checkout_path(lmode, &loid, src_path, &lstate)) {
475 				ret = error("could not write '%s'", src_path);
476 				goto finish;
477 			}
478 		}
479 
480 		if (rmode && !S_ISLNK(rmode)) {
481 			struct working_tree_entry *entry;
482 
483 			/* Avoid duplicate working_tree entries */
484 			FLEX_ALLOC_STR(entry, path, dst_path);
485 			hashmap_entry_init(&entry->entry, strhash(dst_path));
486 			if (hashmap_get(&working_tree_dups, &entry->entry,
487 					NULL)) {
488 				free(entry);
489 				continue;
490 			}
491 			hashmap_add(&working_tree_dups, &entry->entry);
492 
493 			if (!use_wt_file(workdir, dst_path, &roid)) {
494 				if (checkout_path(rmode, &roid, dst_path,
495 						  &rstate)) {
496 					ret = error("could not write '%s'",
497 						    dst_path);
498 					goto finish;
499 				}
500 			} else if (!is_null_oid(&roid)) {
501 				/*
502 				 * Changes in the working tree need special
503 				 * treatment since they are not part of the
504 				 * index.
505 				 */
506 				struct cache_entry *ce2 =
507 					make_cache_entry(&wtindex, rmode, &roid,
508 							 dst_path, 0, 0);
509 
510 				add_index_entry(&wtindex, ce2,
511 						ADD_CACHE_JUST_APPEND);
512 
513 				add_path(&rdir, rdir_len, dst_path);
514 				if (ensure_leading_directories(rdir.buf)) {
515 					ret = error("could not create "
516 						    "directory for '%s'",
517 						    dst_path);
518 					goto finish;
519 				}
520 				add_path(&wtdir, wtdir_len, dst_path);
521 				if (symlinks) {
522 					if (symlink(wtdir.buf, rdir.buf)) {
523 						ret = error_errno("could not symlink '%s' to '%s'", wtdir.buf, rdir.buf);
524 						goto finish;
525 					}
526 				} else {
527 					struct stat st;
528 					if (stat(wtdir.buf, &st))
529 						st.st_mode = 0644;
530 					if (copy_file(rdir.buf, wtdir.buf,
531 						      st.st_mode)) {
532 						ret = error("could not copy '%s' to '%s'", wtdir.buf, rdir.buf);
533 						goto finish;
534 					}
535 				}
536 			}
537 		}
538 	}
539 
540 	fclose(fp);
541 	fp = NULL;
542 	if (finish_command(child)) {
543 		ret = error("error occurred running diff --raw");
544 		goto finish;
545 	}
546 
547 	if (!i)
548 		goto finish;
549 
550 	/*
551 	 * Changes to submodules require special treatment.This loop writes a
552 	 * temporary file to both the left and right directories to show the
553 	 * change in the recorded SHA1 for the submodule.
554 	 */
555 	hashmap_for_each_entry(&submodules, &iter, entry,
556 				entry /* member name */) {
557 		write_standin_files(entry, &ldir, ldir_len, &rdir, rdir_len);
558 	}
559 
560 	/*
561 	 * Symbolic links require special treatment. The standard "git diff"
562 	 * shows only the link itself, not the contents of the link target.
563 	 * This loop replicates that behavior.
564 	 */
565 	hashmap_for_each_entry(&symlinks2, &iter, entry,
566 				entry /* member name */) {
567 
568 		write_standin_files(entry, &ldir, ldir_len, &rdir, rdir_len);
569 	}
570 
571 	strbuf_setlen(&ldir, ldir_len);
572 	helper_argv[1] = ldir.buf;
573 	strbuf_setlen(&rdir, rdir_len);
574 	helper_argv[2] = rdir.buf;
575 
576 	if (extcmd) {
577 		helper_argv[0] = extcmd;
578 		flags = 0;
579 	} else
580 		setenv("GIT_DIFFTOOL_DIRDIFF", "true", 1);
581 	ret = run_command_v_opt(helper_argv, flags);
582 
583 	/* TODO: audit for interaction with sparse-index. */
584 	ensure_full_index(&wtindex);
585 
586 	/*
587 	 * If the diff includes working copy files and those
588 	 * files were modified during the diff, then the changes
589 	 * should be copied back to the working tree.
590 	 * Do not copy back files when symlinks are used and the
591 	 * external tool did not replace the original link with a file.
592 	 *
593 	 * These hashes are loaded lazily since they aren't needed
594 	 * in the common case of --symlinks and the difftool updating
595 	 * files through the symlink.
596 	 */
597 	hashmap_init(&wt_modified, path_entry_cmp, NULL, wtindex.cache_nr);
598 	hashmap_init(&tmp_modified, path_entry_cmp, NULL, wtindex.cache_nr);
599 
600 	for (i = 0; i < wtindex.cache_nr; i++) {
601 		struct hashmap_entry dummy;
602 		const char *name = wtindex.cache[i]->name;
603 		struct stat st;
604 
605 		add_path(&rdir, rdir_len, name);
606 		if (lstat(rdir.buf, &st))
607 			continue;
608 
609 		if ((symlinks && S_ISLNK(st.st_mode)) || !S_ISREG(st.st_mode))
610 			continue;
611 
612 		if (!indices_loaded) {
613 			struct lock_file lock = LOCK_INIT;
614 			strbuf_reset(&buf);
615 			strbuf_addf(&buf, "%s/wtindex", tmpdir.buf);
616 			if (hold_lock_file_for_update(&lock, buf.buf, 0) < 0 ||
617 			    write_locked_index(&wtindex, &lock, COMMIT_LOCK)) {
618 				ret = error("could not write %s", buf.buf);
619 				goto finish;
620 			}
621 			changed_files(&wt_modified, buf.buf, workdir);
622 			strbuf_setlen(&rdir, rdir_len);
623 			changed_files(&tmp_modified, buf.buf, rdir.buf);
624 			add_path(&rdir, rdir_len, name);
625 			indices_loaded = 1;
626 		}
627 
628 		hashmap_entry_init(&dummy, strhash(name));
629 		if (hashmap_get(&tmp_modified, &dummy, name)) {
630 			add_path(&wtdir, wtdir_len, name);
631 			if (hashmap_get(&wt_modified, &dummy, name)) {
632 				warning(_("both files modified: '%s' and '%s'."),
633 					wtdir.buf, rdir.buf);
634 				warning(_("working tree file has been left."));
635 				warning("%s", "");
636 				err = 1;
637 			} else if (unlink(wtdir.buf) ||
638 				   copy_file(wtdir.buf, rdir.buf, st.st_mode))
639 				warning_errno(_("could not copy '%s' to '%s'"),
640 					      rdir.buf, wtdir.buf);
641 		}
642 	}
643 
644 	if (err) {
645 		warning(_("temporary files exist in '%s'."), tmpdir.buf);
646 		warning(_("you may want to cleanup or recover these."));
647 		ret = 1;
648 	} else {
649 		remove_dir_recursively(&tmpdir, 0);
650 		if (ret)
651 			warning(_("failed: %d"), ret);
652 	}
653 
654 finish:
655 	if (fp)
656 		fclose(fp);
657 
658 	free(lbase_dir);
659 	free(rbase_dir);
660 	strbuf_release(&ldir);
661 	strbuf_release(&rdir);
662 	strbuf_release(&wtdir);
663 	strbuf_release(&buf);
664 	strbuf_release(&tmpdir);
665 
666 	return (ret < 0) ? 1 : ret;
667 }
668 
run_file_diff(int prompt,const char * prefix,struct child_process * child)669 static int run_file_diff(int prompt, const char *prefix,
670 			 struct child_process *child)
671 {
672 	const char *env[] = {
673 		"GIT_PAGER=", "GIT_EXTERNAL_DIFF=git-difftool--helper", NULL,
674 		NULL
675 	};
676 
677 	if (prompt > 0)
678 		env[2] = "GIT_DIFFTOOL_PROMPT=true";
679 	else if (!prompt)
680 		env[2] = "GIT_DIFFTOOL_NO_PROMPT=true";
681 
682 	child->git_cmd = 1;
683 	child->dir = prefix;
684 	strvec_pushv(&child->env_array, env);
685 
686 	return run_command(child);
687 }
688 
cmd_difftool(int argc,const char ** argv,const char * prefix)689 int cmd_difftool(int argc, const char **argv, const char *prefix)
690 {
691 	int use_gui_tool = 0, dir_diff = 0, prompt = -1, symlinks = 0,
692 	    tool_help = 0, no_index = 0;
693 	static char *difftool_cmd = NULL, *extcmd = NULL;
694 	struct option builtin_difftool_options[] = {
695 		OPT_BOOL('g', "gui", &use_gui_tool,
696 			 N_("use `diff.guitool` instead of `diff.tool`")),
697 		OPT_BOOL('d', "dir-diff", &dir_diff,
698 			 N_("perform a full-directory diff")),
699 		OPT_SET_INT_F('y', "no-prompt", &prompt,
700 			N_("do not prompt before launching a diff tool"),
701 			0, PARSE_OPT_NONEG),
702 		OPT_SET_INT_F(0, "prompt", &prompt, NULL,
703 			1, PARSE_OPT_NONEG | PARSE_OPT_HIDDEN),
704 		OPT_BOOL(0, "symlinks", &symlinks,
705 			 N_("use symlinks in dir-diff mode")),
706 		OPT_STRING('t', "tool", &difftool_cmd, N_("tool"),
707 			   N_("use the specified diff tool")),
708 		OPT_BOOL(0, "tool-help", &tool_help,
709 			 N_("print a list of diff tools that may be used with "
710 			    "`--tool`")),
711 		OPT_BOOL(0, "trust-exit-code", &trust_exit_code,
712 			 N_("make 'git-difftool' exit when an invoked diff "
713 			    "tool returns a non-zero exit code")),
714 		OPT_STRING('x', "extcmd", &extcmd, N_("command"),
715 			   N_("specify a custom command for viewing diffs")),
716 		OPT_BOOL(0, "no-index", &no_index, N_("passed to `diff`")),
717 		OPT_END()
718 	};
719 	struct child_process child = CHILD_PROCESS_INIT;
720 
721 	git_config(difftool_config, NULL);
722 	symlinks = has_symlinks;
723 
724 	argc = parse_options(argc, argv, prefix, builtin_difftool_options,
725 			     builtin_difftool_usage, PARSE_OPT_KEEP_UNKNOWN |
726 			     PARSE_OPT_KEEP_DASHDASH);
727 
728 	if (tool_help)
729 		return print_tool_help();
730 
731 	if (!no_index && !startup_info->have_repository)
732 		die(_("difftool requires worktree or --no-index"));
733 
734 	if (!no_index){
735 		setup_work_tree();
736 		setenv(GIT_DIR_ENVIRONMENT, absolute_path(get_git_dir()), 1);
737 		setenv(GIT_WORK_TREE_ENVIRONMENT, absolute_path(get_git_work_tree()), 1);
738 	} else if (dir_diff)
739 		die(_("--dir-diff is incompatible with --no-index"));
740 
741 	if (use_gui_tool + !!difftool_cmd + !!extcmd > 1)
742 		die(_("--gui, --tool and --extcmd are mutually exclusive"));
743 
744 	if (use_gui_tool)
745 		setenv("GIT_MERGETOOL_GUI", "true", 1);
746 	else if (difftool_cmd) {
747 		if (*difftool_cmd)
748 			setenv("GIT_DIFF_TOOL", difftool_cmd, 1);
749 		else
750 			die(_("no <tool> given for --tool=<tool>"));
751 	}
752 
753 	if (extcmd) {
754 		if (*extcmd)
755 			setenv("GIT_DIFFTOOL_EXTCMD", extcmd, 1);
756 		else
757 			die(_("no <cmd> given for --extcmd=<cmd>"));
758 	}
759 
760 	setenv("GIT_DIFFTOOL_TRUST_EXIT_CODE",
761 	       trust_exit_code ? "true" : "false", 1);
762 
763 	/*
764 	 * In directory diff mode, 'git-difftool--helper' is called once
765 	 * to compare the a / b directories. In file diff mode, 'git diff'
766 	 * will invoke a separate instance of 'git-difftool--helper' for
767 	 * each file that changed.
768 	 */
769 	strvec_push(&child.args, "diff");
770 	if (no_index)
771 		strvec_push(&child.args, "--no-index");
772 	if (dir_diff)
773 		strvec_pushl(&child.args, "--raw", "--no-abbrev", "-z", NULL);
774 	strvec_pushv(&child.args, argv);
775 
776 	if (dir_diff)
777 		return run_dir_diff(extcmd, symlinks, prefix, &child);
778 	return run_file_diff(prompt, prefix, &child);
779 }
780