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