2 * "git difftool" builtin command
4 * This is a wrapper around the GIT_EXTERNAL_DIFF-compatible
5 * git-difftool--helper script.
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.
10 * Any arguments that are unknown to this script are forwarded to 'git diff'.
12 * Copyright (C) 2016 Johannes Schindelin
17 #include "run-command.h"
19 #include "parse-options.h"
20 #include "argv-array.h"
25 static char *diff_gui_tool;
26 static int trust_exit_code;
28 static const char *const builtin_difftool_usage[] = {
29 N_("git difftool [<options>] [<commit> [<commit>]] [--] [<path>...]"),
33 static int difftool_config(const char *var, const char *value, void *cb)
35 if (!strcmp(var, "diff.guitool")) {
36 diff_gui_tool = xstrdup(value);
40 if (!strcmp(var, "difftool.trustexitcode")) {
41 trust_exit_code = git_config_bool(var, value);
45 return git_default_config(var, value, cb);
48 static int print_tool_help(void)
50 const char *argv[] = { "mergetool", "--tool-help=diff", NULL };
51 return run_command_v_opt(argv, RUN_GIT_CMD);
54 static int parse_index_info(char *p, int *mode1, int *mode2,
55 struct object_id *oid1, struct object_id *oid2,
59 return error("expected ':', got '%c'", *p);
60 *mode1 = (int)strtol(p + 1, &p, 8);
62 return error("expected ' ', got '%c'", *p);
63 *mode2 = (int)strtol(p + 1, &p, 8);
65 return error("expected ' ', got '%c'", *p);
66 if (get_oid_hex(++p, oid1))
67 return error("expected object ID, got '%s'", p + 1);
70 return error("expected ' ', got '%c'", *p);
71 if (get_oid_hex(++p, oid2))
72 return error("expected object ID, got '%s'", p + 1);
75 return error("expected ' ', got '%c'", *p);
78 return error("missing status");
79 if (p[1] && !isdigit(p[1]))
80 return error("unexpected trailer: '%s'", p + 1);
85 * Remove any trailing slash from $workdir
86 * before starting to avoid double slashes in symlink targets.
88 static void add_path(struct strbuf *buf, size_t base_len, const char *path)
90 strbuf_setlen(buf, base_len);
91 if (buf->len && buf->buf[buf->len - 1] != '/')
92 strbuf_addch(buf, '/');
93 strbuf_addstr(buf, path);
97 * Determine whether we can simply reuse the file in the worktree.
99 static int use_wt_file(const char *workdir, const char *name,
100 struct object_id *oid)
102 struct strbuf buf = STRBUF_INIT;
106 strbuf_addstr(&buf, workdir);
107 add_path(&buf, buf.len, name);
109 if (!lstat(buf.buf, &st) && !S_ISLNK(st.st_mode)) {
110 struct object_id wt_oid;
111 int fd = open(buf.buf, O_RDONLY);
114 !index_fd(wt_oid.hash, fd, &st, OBJ_BLOB, name, 0)) {
115 if (is_null_oid(oid)) {
116 oidcpy(oid, &wt_oid);
118 } else if (!oidcmp(oid, &wt_oid))
123 strbuf_release(&buf);
128 struct working_tree_entry {
129 struct hashmap_entry entry;
130 char path[FLEX_ARRAY];
133 static int working_tree_entry_cmp(const void *unused_cmp_data,
134 struct working_tree_entry *a,
135 struct working_tree_entry *b,
136 void *unused_keydata)
138 return strcmp(a->path, b->path);
142 * The `left` and `right` entries hold paths for the symlinks hashmap,
143 * and a SHA-1 surrounded by brief text for submodules.
146 struct hashmap_entry entry;
147 char left[PATH_MAX], right[PATH_MAX];
148 const char path[FLEX_ARRAY];
151 static int pair_cmp(const void *unused_cmp_data,
152 struct pair_entry *a, struct pair_entry *b,
153 void *unused_keydata)
155 return strcmp(a->path, b->path);
158 static void add_left_or_right(struct hashmap *map, const char *path,
159 const char *content, int is_right)
161 struct pair_entry *e, *existing;
163 FLEX_ALLOC_STR(e, path, path);
164 hashmap_entry_init(e, strhash(path));
165 existing = hashmap_get(map, e, NULL);
170 e->left[0] = e->right[0] = '\0';
173 strlcpy(is_right ? e->right : e->left, content, PATH_MAX);
177 struct hashmap_entry entry;
178 char path[FLEX_ARRAY];
181 static int path_entry_cmp(const void *unused_cmp_data,
182 struct path_entry *a, struct path_entry *b,
185 return strcmp(a->path, key ? key : b->path);
188 static void changed_files(struct hashmap *result, const char *index_path,
191 struct child_process update_index = CHILD_PROCESS_INIT;
192 struct child_process diff_files = CHILD_PROCESS_INIT;
193 struct strbuf index_env = STRBUF_INIT, buf = STRBUF_INIT;
194 const char *git_dir = absolute_path(get_git_dir()), *env[] = {
199 strbuf_addf(&index_env, "GIT_INDEX_FILE=%s", index_path);
200 env[0] = index_env.buf;
202 argv_array_pushl(&update_index.args,
203 "--git-dir", git_dir, "--work-tree", workdir,
204 "update-index", "--really-refresh", "-q",
206 update_index.no_stdin = 1;
207 update_index.no_stdout = 1;
208 update_index.no_stderr = 1;
209 update_index.git_cmd = 1;
210 update_index.use_shell = 0;
211 update_index.clean_on_exit = 1;
212 update_index.dir = workdir;
213 update_index.env = env;
214 /* Ignore any errors of update-index */
215 run_command(&update_index);
217 argv_array_pushl(&diff_files.args,
218 "--git-dir", git_dir, "--work-tree", workdir,
219 "diff-files", "--name-only", "-z", NULL);
220 diff_files.no_stdin = 1;
221 diff_files.git_cmd = 1;
222 diff_files.use_shell = 0;
223 diff_files.clean_on_exit = 1;
225 diff_files.dir = workdir;
226 diff_files.env = env;
227 if (start_command(&diff_files))
228 die("could not obtain raw diff");
229 fp = xfdopen(diff_files.out, "r");
230 while (!strbuf_getline_nul(&buf, fp)) {
231 struct path_entry *entry;
232 FLEX_ALLOC_STR(entry, path, buf.buf);
233 hashmap_entry_init(entry, strhash(buf.buf));
234 hashmap_add(result, entry);
237 if (finish_command(&diff_files))
238 die("diff-files did not exit properly");
239 strbuf_release(&index_env);
240 strbuf_release(&buf);
243 static NORETURN void exit_cleanup(const char *tmpdir, int exit_code)
245 struct strbuf buf = STRBUF_INIT;
246 strbuf_addstr(&buf, tmpdir);
247 remove_dir_recursively(&buf, 0);
249 warning(_("failed: %d"), exit_code);
253 static int ensure_leading_directories(char *path)
255 switch (safe_create_leading_directories(path)) {
260 return error(_("could not create leading directories "
266 * Unconditional writing of a plain regular file is what
267 * "git difftool --dir-diff" wants to do for symlinks. We are preparing two
268 * temporary directories to be fed to a Git-unaware tool that knows how to
269 * show a diff of two directories (e.g. "diff -r A B").
271 * Because the tool is Git-unaware, if a symbolic link appears in either of
272 * these temporary directories, it will try to dereference and show the
273 * difference of the target of the symbolic link, which is not what we want,
274 * as the goal of the dir-diff mode is to produce an output that is logically
275 * equivalent to what "git diff" produces.
277 * Most importantly, we want to get textual comparison of the result of the
278 * readlink(2). get_symlink() provides that---it returns the contents of
279 * the symlink that gets written to a regular file to force the external tool
280 * to compare the readlink(2) result as text, even on a filesystem that is
281 * capable of doing a symbolic link.
283 static char *get_symlink(const struct object_id *oid, const char *path)
286 if (is_null_oid(oid)) {
287 /* The symlink is unknown to Git so read from the filesystem */
288 struct strbuf link = STRBUF_INIT;
290 if (strbuf_readlink(&link, path, strlen(path)))
291 die(_("could not read symlink %s"), path);
292 } else if (strbuf_read_file(&link, path, 128))
293 die(_("could not read symlink file %s"), path);
295 data = strbuf_detach(&link, NULL);
297 enum object_type type;
299 data = read_sha1_file(oid->hash, &type, &size);
301 die(_("could not read object %s for symlink %s"),
302 oid_to_hex(oid), path);
308 static int checkout_path(unsigned mode, struct object_id *oid,
309 const char *path, const struct checkout *state)
311 struct cache_entry *ce;
314 ce = make_cache_entry(mode, oid->hash, path, 0, 0);
315 ret = checkout_entry(ce, state, NULL);
321 static int run_dir_diff(const char *extcmd, int symlinks, const char *prefix,
322 int argc, const char **argv)
324 char tmpdir[PATH_MAX];
325 struct strbuf info = STRBUF_INIT, lpath = STRBUF_INIT;
326 struct strbuf rpath = STRBUF_INIT, buf = STRBUF_INIT;
327 struct strbuf ldir = STRBUF_INIT, rdir = STRBUF_INIT;
328 struct strbuf wtdir = STRBUF_INIT;
329 char *lbase_dir, *rbase_dir;
330 size_t ldir_len, rdir_len, wtdir_len;
331 const char *workdir, *tmp;
334 struct hashmap working_tree_dups, submodules, symlinks2;
335 struct hashmap_iter iter;
336 struct pair_entry *entry;
337 struct index_state wtindex;
338 struct checkout lstate, rstate;
339 int rc, flags = RUN_GIT_CMD, err = 0;
340 struct child_process child = CHILD_PROCESS_INIT;
341 const char *helper_argv[] = { "difftool--helper", NULL, NULL, NULL };
342 struct hashmap wt_modified, tmp_modified;
343 int indices_loaded = 0;
345 workdir = get_git_work_tree();
347 /* Setup temp directories */
348 tmp = getenv("TMPDIR");
349 xsnprintf(tmpdir, sizeof(tmpdir), "%s/git-difftool.XXXXXX", tmp ? tmp : "/tmp");
350 if (!mkdtemp(tmpdir))
351 return error("could not create '%s'", tmpdir);
352 strbuf_addf(&ldir, "%s/left/", tmpdir);
353 strbuf_addf(&rdir, "%s/right/", tmpdir);
354 strbuf_addstr(&wtdir, workdir);
355 if (!wtdir.len || !is_dir_sep(wtdir.buf[wtdir.len - 1]))
356 strbuf_addch(&wtdir, '/');
357 mkdir(ldir.buf, 0700);
358 mkdir(rdir.buf, 0700);
360 memset(&wtindex, 0, sizeof(wtindex));
362 memset(&lstate, 0, sizeof(lstate));
363 lstate.base_dir = lbase_dir = xstrdup(ldir.buf);
364 lstate.base_dir_len = ldir.len;
366 memset(&rstate, 0, sizeof(rstate));
367 rstate.base_dir = rbase_dir = xstrdup(rdir.buf);
368 rstate.base_dir_len = rdir.len;
373 wtdir_len = wtdir.len;
375 hashmap_init(&working_tree_dups,
376 (hashmap_cmp_fn)working_tree_entry_cmp, NULL, 0);
377 hashmap_init(&submodules, (hashmap_cmp_fn)pair_cmp, NULL, 0);
378 hashmap_init(&symlinks2, (hashmap_cmp_fn)pair_cmp, NULL, 0);
383 child.clean_on_exit = 1;
386 argv_array_pushl(&child.args, "diff", "--raw", "--no-abbrev", "-z",
388 for (i = 0; i < argc; i++)
389 argv_array_push(&child.args, argv[i]);
390 if (start_command(&child))
391 die("could not obtain raw diff");
392 fp = xfdopen(child.out, "r");
394 /* Build index info for left and right sides of the diff */
396 while (!strbuf_getline_nul(&info, fp)) {
398 struct object_id loid, roid;
400 const char *src_path, *dst_path;
402 if (starts_with(info.buf, "::"))
403 die(N_("combined diff formats('-c' and '--cc') are "
405 "directory diff mode('-d' and '--dir-diff')."));
407 if (parse_index_info(info.buf, &lmode, &rmode, &loid, &roid,
410 if (strbuf_getline_nul(&lpath, fp))
412 src_path = lpath.buf;
415 if (status != 'C' && status != 'R') {
418 if (strbuf_getline_nul(&rpath, fp))
420 dst_path = rpath.buf;
423 if (S_ISGITLINK(lmode) || S_ISGITLINK(rmode)) {
425 strbuf_addf(&buf, "Subproject commit %s",
427 add_left_or_right(&submodules, src_path, buf.buf, 0);
429 strbuf_addf(&buf, "Subproject commit %s",
431 if (!oidcmp(&loid, &roid))
432 strbuf_addstr(&buf, "-dirty");
433 add_left_or_right(&submodules, dst_path, buf.buf, 1);
437 if (S_ISLNK(lmode)) {
438 char *content = get_symlink(&loid, src_path);
439 add_left_or_right(&symlinks2, src_path, content, 0);
443 if (S_ISLNK(rmode)) {
444 char *content = get_symlink(&roid, dst_path);
445 add_left_or_right(&symlinks2, dst_path, content, 1);
449 if (lmode && status != 'C') {
450 if (checkout_path(lmode, &loid, src_path, &lstate)) {
451 ret = error("could not write '%s'", src_path);
456 if (rmode && !S_ISLNK(rmode)) {
457 struct working_tree_entry *entry;
459 /* Avoid duplicate working_tree entries */
460 FLEX_ALLOC_STR(entry, path, dst_path);
461 hashmap_entry_init(entry, strhash(dst_path));
462 if (hashmap_get(&working_tree_dups, entry, NULL)) {
466 hashmap_add(&working_tree_dups, entry);
468 if (!use_wt_file(workdir, dst_path, &roid)) {
469 if (checkout_path(rmode, &roid, dst_path,
471 ret = error("could not write '%s'",
475 } else if (!is_null_oid(&roid)) {
477 * Changes in the working tree need special
478 * treatment since they are not part of the
481 struct cache_entry *ce2 =
482 make_cache_entry(rmode, roid.hash,
485 add_index_entry(&wtindex, ce2,
486 ADD_CACHE_JUST_APPEND);
488 add_path(&rdir, rdir_len, dst_path);
489 if (ensure_leading_directories(rdir.buf)) {
490 ret = error("could not create "
491 "directory for '%s'",
495 add_path(&wtdir, wtdir_len, dst_path);
497 if (symlink(wtdir.buf, rdir.buf)) {
498 ret = error_errno("could not symlink '%s' to '%s'", wtdir.buf, rdir.buf);
503 if (stat(wtdir.buf, &st))
505 if (copy_file(rdir.buf, wtdir.buf,
507 ret = error("could not copy '%s' to '%s'", wtdir.buf, rdir.buf);
517 if (finish_command(&child)) {
518 ret = error("error occurred running diff --raw");
526 * Changes to submodules require special treatment.This loop writes a
527 * temporary file to both the left and right directories to show the
528 * change in the recorded SHA1 for the submodule.
530 hashmap_iter_init(&submodules, &iter);
531 while ((entry = hashmap_iter_next(&iter))) {
533 add_path(&ldir, ldir_len, entry->path);
534 ensure_leading_directories(ldir.buf);
535 write_file(ldir.buf, "%s", entry->left);
538 add_path(&rdir, rdir_len, entry->path);
539 ensure_leading_directories(rdir.buf);
540 write_file(rdir.buf, "%s", entry->right);
545 * Symbolic links require special treatment.The standard "git diff"
546 * shows only the link itself, not the contents of the link target.
547 * This loop replicates that behavior.
549 hashmap_iter_init(&symlinks2, &iter);
550 while ((entry = hashmap_iter_next(&iter))) {
552 add_path(&ldir, ldir_len, entry->path);
553 ensure_leading_directories(ldir.buf);
554 write_file(ldir.buf, "%s", entry->left);
557 add_path(&rdir, rdir_len, entry->path);
558 ensure_leading_directories(rdir.buf);
559 write_file(rdir.buf, "%s", entry->right);
563 strbuf_release(&buf);
565 strbuf_setlen(&ldir, ldir_len);
566 helper_argv[1] = ldir.buf;
567 strbuf_setlen(&rdir, rdir_len);
568 helper_argv[2] = rdir.buf;
571 helper_argv[0] = extcmd;
574 setenv("GIT_DIFFTOOL_DIRDIFF", "true", 1);
575 rc = run_command_v_opt(helper_argv, flags);
578 * If the diff includes working copy files and those
579 * files were modified during the diff, then the changes
580 * should be copied back to the working tree.
581 * Do not copy back files when symlinks are used and the
582 * external tool did not replace the original link with a file.
584 * These hashes are loaded lazily since they aren't needed
585 * in the common case of --symlinks and the difftool updating
586 * files through the symlink.
588 hashmap_init(&wt_modified, (hashmap_cmp_fn)path_entry_cmp,
589 NULL, wtindex.cache_nr);
590 hashmap_init(&tmp_modified, (hashmap_cmp_fn)path_entry_cmp,
591 NULL, wtindex.cache_nr);
593 for (i = 0; i < wtindex.cache_nr; i++) {
594 struct hashmap_entry dummy;
595 const char *name = wtindex.cache[i]->name;
598 add_path(&rdir, rdir_len, name);
599 if (lstat(rdir.buf, &st))
602 if ((symlinks && S_ISLNK(st.st_mode)) || !S_ISREG(st.st_mode))
605 if (!indices_loaded) {
606 static struct lock_file lock;
608 strbuf_addf(&buf, "%s/wtindex", tmpdir);
609 if (hold_lock_file_for_update(&lock, buf.buf, 0) < 0 ||
610 write_locked_index(&wtindex, &lock, COMMIT_LOCK)) {
611 ret = error("could not write %s", buf.buf);
612 rollback_lock_file(&lock);
615 changed_files(&wt_modified, buf.buf, workdir);
616 strbuf_setlen(&rdir, rdir_len);
617 changed_files(&tmp_modified, buf.buf, rdir.buf);
618 add_path(&rdir, rdir_len, name);
622 hashmap_entry_init(&dummy, strhash(name));
623 if (hashmap_get(&tmp_modified, &dummy, name)) {
624 add_path(&wtdir, wtdir_len, name);
625 if (hashmap_get(&wt_modified, &dummy, name)) {
626 warning(_("both files modified: '%s' and '%s'."),
627 wtdir.buf, rdir.buf);
628 warning(_("working tree file has been left."));
631 } else if (unlink(wtdir.buf) ||
632 copy_file(wtdir.buf, rdir.buf, st.st_mode))
633 warning_errno(_("could not copy '%s' to '%s'"),
634 rdir.buf, wtdir.buf);
639 warning(_("temporary files exist in '%s'."), tmpdir);
640 warning(_("you may want to cleanup or recover these."));
643 exit_cleanup(tmpdir, rc);
651 strbuf_release(&ldir);
652 strbuf_release(&rdir);
653 strbuf_release(&wtdir);
654 strbuf_release(&buf);
659 static int run_file_diff(int prompt, const char *prefix,
660 int argc, const char **argv)
662 struct argv_array args = ARGV_ARRAY_INIT;
663 const char *env[] = {
664 "GIT_PAGER=", "GIT_EXTERNAL_DIFF=git-difftool--helper", NULL,
670 env[2] = "GIT_DIFFTOOL_PROMPT=true";
672 env[2] = "GIT_DIFFTOOL_NO_PROMPT=true";
675 argv_array_push(&args, "diff");
676 for (i = 0; i < argc; i++)
677 argv_array_push(&args, argv[i]);
678 ret = run_command_v_opt_cd_env(args.argv, RUN_GIT_CMD, prefix, env);
682 int cmd_difftool(int argc, const char **argv, const char *prefix)
684 int use_gui_tool = 0, dir_diff = 0, prompt = -1, symlinks = 0,
686 static char *difftool_cmd = NULL, *extcmd = NULL;
687 struct option builtin_difftool_options[] = {
688 OPT_BOOL('g', "gui", &use_gui_tool,
689 N_("use `diff.guitool` instead of `diff.tool`")),
690 OPT_BOOL('d', "dir-diff", &dir_diff,
691 N_("perform a full-directory diff")),
692 { OPTION_SET_INT, 'y', "no-prompt", &prompt, NULL,
693 N_("do not prompt before launching a diff tool"),
694 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 0},
695 { OPTION_SET_INT, 0, "prompt", &prompt, NULL, NULL,
696 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_HIDDEN,
698 OPT_BOOL(0, "symlinks", &symlinks,
699 N_("use symlinks in dir-diff mode")),
700 OPT_STRING('t', "tool", &difftool_cmd, N_("<tool>"),
701 N_("use the specified diff tool")),
702 OPT_BOOL(0, "tool-help", &tool_help,
703 N_("print a list of diff tools that may be used with "
705 OPT_BOOL(0, "trust-exit-code", &trust_exit_code,
706 N_("make 'git-difftool' exit when an invoked diff "
707 "tool returns a non - zero exit code")),
708 OPT_STRING('x', "extcmd", &extcmd, N_("<command>"),
709 N_("specify a custom command for viewing diffs")),
713 git_config(difftool_config, NULL);
714 symlinks = has_symlinks;
716 argc = parse_options(argc, argv, prefix, builtin_difftool_options,
717 builtin_difftool_usage, PARSE_OPT_KEEP_UNKNOWN |
718 PARSE_OPT_KEEP_DASHDASH);
721 return print_tool_help();
723 /* NEEDSWORK: once we no longer spawn anything, remove this */
724 setenv(GIT_DIR_ENVIRONMENT, absolute_path(get_git_dir()), 1);
725 setenv(GIT_WORK_TREE_ENVIRONMENT, absolute_path(get_git_work_tree()), 1);
727 if (use_gui_tool && diff_gui_tool && *diff_gui_tool)
728 setenv("GIT_DIFF_TOOL", diff_gui_tool, 1);
729 else if (difftool_cmd) {
731 setenv("GIT_DIFF_TOOL", difftool_cmd, 1);
733 die(_("no <tool> given for --tool=<tool>"));
738 setenv("GIT_DIFFTOOL_EXTCMD", extcmd, 1);
740 die(_("no <cmd> given for --extcmd=<cmd>"));
743 setenv("GIT_DIFFTOOL_TRUST_EXIT_CODE",
744 trust_exit_code ? "true" : "false", 1);
747 * In directory diff mode, 'git-difftool--helper' is called once
748 * to compare the a / b directories. In file diff mode, 'git diff'
749 * will invoke a separate instance of 'git-difftool--helper' for
750 * each file that changed.
753 return run_dir_diff(extcmd, symlinks, prefix, argc, argv);
754 return run_file_diff(prompt, prefix, argc, argv);