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"
23 #include "object-store.h"
26 static char *diff_gui_tool;
27 static int trust_exit_code;
29 static const char *const builtin_difftool_usage[] = {
30 N_("git difftool [<options>] [<commit> [<commit>]] [--] [<path>...]"),
34 static int difftool_config(const char *var, const char *value, void *cb)
36 if (!strcmp(var, "diff.guitool")) {
37 diff_gui_tool = xstrdup(value);
41 if (!strcmp(var, "difftool.trustexitcode")) {
42 trust_exit_code = git_config_bool(var, value);
46 return git_default_config(var, value, cb);
49 static int print_tool_help(void)
51 const char *argv[] = { "mergetool", "--tool-help=diff", NULL };
52 return run_command_v_opt(argv, RUN_GIT_CMD);
55 static int parse_index_info(char *p, int *mode1, int *mode2,
56 struct object_id *oid1, struct object_id *oid2,
60 return error("expected ':', got '%c'", *p);
61 *mode1 = (int)strtol(p + 1, &p, 8);
63 return error("expected ' ', got '%c'", *p);
64 *mode2 = (int)strtol(p + 1, &p, 8);
66 return error("expected ' ', got '%c'", *p);
67 if (get_oid_hex(++p, oid1))
68 return error("expected object ID, got '%s'", p + 1);
71 return error("expected ' ', got '%c'", *p);
72 if (get_oid_hex(++p, oid2))
73 return error("expected object ID, got '%s'", p + 1);
76 return error("expected ' ', got '%c'", *p);
79 return error("missing status");
80 if (p[1] && !isdigit(p[1]))
81 return error("unexpected trailer: '%s'", p + 1);
86 * Remove any trailing slash from $workdir
87 * before starting to avoid double slashes in symlink targets.
89 static void add_path(struct strbuf *buf, size_t base_len, const char *path)
91 strbuf_setlen(buf, base_len);
92 if (buf->len && buf->buf[buf->len - 1] != '/')
93 strbuf_addch(buf, '/');
94 strbuf_addstr(buf, path);
98 * Determine whether we can simply reuse the file in the worktree.
100 static int use_wt_file(const char *workdir, const char *name,
101 struct object_id *oid)
103 struct strbuf buf = STRBUF_INIT;
107 strbuf_addstr(&buf, workdir);
108 add_path(&buf, buf.len, name);
110 if (!lstat(buf.buf, &st) && !S_ISLNK(st.st_mode)) {
111 struct object_id wt_oid;
112 int fd = open(buf.buf, O_RDONLY);
115 !index_fd(&the_index, &wt_oid, fd, &st, OBJ_BLOB, name, 0)) {
116 if (is_null_oid(oid)) {
117 oidcpy(oid, &wt_oid);
119 } else if (oideq(oid, &wt_oid))
124 strbuf_release(&buf);
129 struct working_tree_entry {
130 struct hashmap_entry entry;
131 char path[FLEX_ARRAY];
134 static int working_tree_entry_cmp(const void *unused_cmp_data,
136 const void *entry_or_key,
137 const void *unused_keydata)
139 const struct working_tree_entry *a = entry;
140 const struct working_tree_entry *b = entry_or_key;
141 return strcmp(a->path, b->path);
145 * The `left` and `right` entries hold paths for the symlinks hashmap,
146 * and a SHA-1 surrounded by brief text for submodules.
149 struct hashmap_entry entry;
150 char left[PATH_MAX], right[PATH_MAX];
151 const char path[FLEX_ARRAY];
154 static int pair_cmp(const void *unused_cmp_data,
156 const void *entry_or_key,
157 const void *unused_keydata)
159 const struct pair_entry *a = entry;
160 const struct pair_entry *b = entry_or_key;
162 return strcmp(a->path, b->path);
165 static void add_left_or_right(struct hashmap *map, const char *path,
166 const char *content, int is_right)
168 struct pair_entry *e, *existing;
170 FLEX_ALLOC_STR(e, path, path);
171 hashmap_entry_init(e, strhash(path));
172 existing = hashmap_get(map, e, NULL);
177 e->left[0] = e->right[0] = '\0';
180 strlcpy(is_right ? e->right : e->left, content, PATH_MAX);
184 struct hashmap_entry entry;
185 char path[FLEX_ARRAY];
188 static int path_entry_cmp(const void *unused_cmp_data,
190 const void *entry_or_key,
193 const struct path_entry *a = entry;
194 const struct path_entry *b = entry_or_key;
196 return strcmp(a->path, key ? key : b->path);
199 static void changed_files(struct hashmap *result, const char *index_path,
202 struct child_process update_index = CHILD_PROCESS_INIT;
203 struct child_process diff_files = CHILD_PROCESS_INIT;
204 struct strbuf index_env = STRBUF_INIT, buf = STRBUF_INIT;
205 const char *git_dir = absolute_path(get_git_dir()), *env[] = {
210 strbuf_addf(&index_env, "GIT_INDEX_FILE=%s", index_path);
211 env[0] = index_env.buf;
213 argv_array_pushl(&update_index.args,
214 "--git-dir", git_dir, "--work-tree", workdir,
215 "update-index", "--really-refresh", "-q",
217 update_index.no_stdin = 1;
218 update_index.no_stdout = 1;
219 update_index.no_stderr = 1;
220 update_index.git_cmd = 1;
221 update_index.use_shell = 0;
222 update_index.clean_on_exit = 1;
223 update_index.dir = workdir;
224 update_index.env = env;
225 /* Ignore any errors of update-index */
226 run_command(&update_index);
228 argv_array_pushl(&diff_files.args,
229 "--git-dir", git_dir, "--work-tree", workdir,
230 "diff-files", "--name-only", "-z", NULL);
231 diff_files.no_stdin = 1;
232 diff_files.git_cmd = 1;
233 diff_files.use_shell = 0;
234 diff_files.clean_on_exit = 1;
236 diff_files.dir = workdir;
237 diff_files.env = env;
238 if (start_command(&diff_files))
239 die("could not obtain raw diff");
240 fp = xfdopen(diff_files.out, "r");
241 while (!strbuf_getline_nul(&buf, fp)) {
242 struct path_entry *entry;
243 FLEX_ALLOC_STR(entry, path, buf.buf);
244 hashmap_entry_init(entry, strhash(buf.buf));
245 hashmap_add(result, entry);
248 if (finish_command(&diff_files))
249 die("diff-files did not exit properly");
250 strbuf_release(&index_env);
251 strbuf_release(&buf);
254 static NORETURN void exit_cleanup(const char *tmpdir, int exit_code)
256 struct strbuf buf = STRBUF_INIT;
257 strbuf_addstr(&buf, tmpdir);
258 remove_dir_recursively(&buf, 0);
260 warning(_("failed: %d"), exit_code);
264 static int ensure_leading_directories(char *path)
266 switch (safe_create_leading_directories(path)) {
271 return error(_("could not create leading directories "
277 * Unconditional writing of a plain regular file is what
278 * "git difftool --dir-diff" wants to do for symlinks. We are preparing two
279 * temporary directories to be fed to a Git-unaware tool that knows how to
280 * show a diff of two directories (e.g. "diff -r A B").
282 * Because the tool is Git-unaware, if a symbolic link appears in either of
283 * these temporary directories, it will try to dereference and show the
284 * difference of the target of the symbolic link, which is not what we want,
285 * as the goal of the dir-diff mode is to produce an output that is logically
286 * equivalent to what "git diff" produces.
288 * Most importantly, we want to get textual comparison of the result of the
289 * readlink(2). get_symlink() provides that---it returns the contents of
290 * the symlink that gets written to a regular file to force the external tool
291 * to compare the readlink(2) result as text, even on a filesystem that is
292 * capable of doing a symbolic link.
294 static char *get_symlink(const struct object_id *oid, const char *path)
297 if (is_null_oid(oid)) {
298 /* The symlink is unknown to Git so read from the filesystem */
299 struct strbuf link = STRBUF_INIT;
301 if (strbuf_readlink(&link, path, strlen(path)))
302 die(_("could not read symlink %s"), path);
303 } else if (strbuf_read_file(&link, path, 128))
304 die(_("could not read symlink file %s"), path);
306 data = strbuf_detach(&link, NULL);
308 enum object_type type;
310 data = read_object_file(oid, &type, &size);
312 die(_("could not read object %s for symlink %s"),
313 oid_to_hex(oid), path);
319 static int checkout_path(unsigned mode, struct object_id *oid,
320 const char *path, const struct checkout *state)
322 struct cache_entry *ce;
325 ce = make_transient_cache_entry(mode, oid, path, 0);
326 ret = checkout_entry(ce, state, NULL, NULL);
328 discard_cache_entry(ce);
332 static int run_dir_diff(const char *extcmd, int symlinks, const char *prefix,
333 int argc, const char **argv)
335 char tmpdir[PATH_MAX];
336 struct strbuf info = STRBUF_INIT, lpath = STRBUF_INIT;
337 struct strbuf rpath = STRBUF_INIT, buf = STRBUF_INIT;
338 struct strbuf ldir = STRBUF_INIT, rdir = STRBUF_INIT;
339 struct strbuf wtdir = STRBUF_INIT;
340 char *lbase_dir, *rbase_dir;
341 size_t ldir_len, rdir_len, wtdir_len;
342 const char *workdir, *tmp;
345 struct hashmap working_tree_dups, submodules, symlinks2;
346 struct hashmap_iter iter;
347 struct pair_entry *entry;
348 struct index_state wtindex;
349 struct checkout lstate, rstate;
350 int rc, flags = RUN_GIT_CMD, err = 0;
351 struct child_process child = CHILD_PROCESS_INIT;
352 const char *helper_argv[] = { "difftool--helper", NULL, NULL, NULL };
353 struct hashmap wt_modified, tmp_modified;
354 int indices_loaded = 0;
356 workdir = get_git_work_tree();
358 /* Setup temp directories */
359 tmp = getenv("TMPDIR");
360 xsnprintf(tmpdir, sizeof(tmpdir), "%s/git-difftool.XXXXXX", tmp ? tmp : "/tmp");
361 if (!mkdtemp(tmpdir))
362 return error("could not create '%s'", tmpdir);
363 strbuf_addf(&ldir, "%s/left/", tmpdir);
364 strbuf_addf(&rdir, "%s/right/", tmpdir);
365 strbuf_addstr(&wtdir, workdir);
366 if (!wtdir.len || !is_dir_sep(wtdir.buf[wtdir.len - 1]))
367 strbuf_addch(&wtdir, '/');
368 mkdir(ldir.buf, 0700);
369 mkdir(rdir.buf, 0700);
371 memset(&wtindex, 0, sizeof(wtindex));
373 memset(&lstate, 0, sizeof(lstate));
374 lstate.base_dir = lbase_dir = xstrdup(ldir.buf);
375 lstate.base_dir_len = ldir.len;
377 memset(&rstate, 0, sizeof(rstate));
378 rstate.base_dir = rbase_dir = xstrdup(rdir.buf);
379 rstate.base_dir_len = rdir.len;
384 wtdir_len = wtdir.len;
386 hashmap_init(&working_tree_dups, working_tree_entry_cmp, NULL, 0);
387 hashmap_init(&submodules, pair_cmp, NULL, 0);
388 hashmap_init(&symlinks2, pair_cmp, NULL, 0);
393 child.clean_on_exit = 1;
396 argv_array_pushl(&child.args, "diff", "--raw", "--no-abbrev", "-z",
398 for (i = 0; i < argc; i++)
399 argv_array_push(&child.args, argv[i]);
400 if (start_command(&child))
401 die("could not obtain raw diff");
402 fp = xfdopen(child.out, "r");
404 /* Build index info for left and right sides of the diff */
406 while (!strbuf_getline_nul(&info, fp)) {
408 struct object_id loid, roid;
410 const char *src_path, *dst_path;
412 if (starts_with(info.buf, "::"))
413 die(N_("combined diff formats('-c' and '--cc') are "
415 "directory diff mode('-d' and '--dir-diff')."));
417 if (parse_index_info(info.buf, &lmode, &rmode, &loid, &roid,
420 if (strbuf_getline_nul(&lpath, fp))
422 src_path = lpath.buf;
425 if (status != 'C' && status != 'R') {
428 if (strbuf_getline_nul(&rpath, fp))
430 dst_path = rpath.buf;
433 if (S_ISGITLINK(lmode) || S_ISGITLINK(rmode)) {
435 strbuf_addf(&buf, "Subproject commit %s",
437 add_left_or_right(&submodules, src_path, buf.buf, 0);
439 strbuf_addf(&buf, "Subproject commit %s",
441 if (oideq(&loid, &roid))
442 strbuf_addstr(&buf, "-dirty");
443 add_left_or_right(&submodules, dst_path, buf.buf, 1);
447 if (S_ISLNK(lmode)) {
448 char *content = get_symlink(&loid, src_path);
449 add_left_or_right(&symlinks2, src_path, content, 0);
453 if (S_ISLNK(rmode)) {
454 char *content = get_symlink(&roid, dst_path);
455 add_left_or_right(&symlinks2, dst_path, content, 1);
459 if (lmode && status != 'C') {
460 if (checkout_path(lmode, &loid, src_path, &lstate)) {
461 ret = error("could not write '%s'", src_path);
466 if (rmode && !S_ISLNK(rmode)) {
467 struct working_tree_entry *entry;
469 /* Avoid duplicate working_tree entries */
470 FLEX_ALLOC_STR(entry, path, dst_path);
471 hashmap_entry_init(entry, strhash(dst_path));
472 if (hashmap_get(&working_tree_dups, entry, NULL)) {
476 hashmap_add(&working_tree_dups, entry);
478 if (!use_wt_file(workdir, dst_path, &roid)) {
479 if (checkout_path(rmode, &roid, dst_path,
481 ret = error("could not write '%s'",
485 } else if (!is_null_oid(&roid)) {
487 * Changes in the working tree need special
488 * treatment since they are not part of the
491 struct cache_entry *ce2 =
492 make_cache_entry(&wtindex, rmode, &roid,
495 add_index_entry(&wtindex, ce2,
496 ADD_CACHE_JUST_APPEND);
498 add_path(&rdir, rdir_len, dst_path);
499 if (ensure_leading_directories(rdir.buf)) {
500 ret = error("could not create "
501 "directory for '%s'",
505 add_path(&wtdir, wtdir_len, dst_path);
507 if (symlink(wtdir.buf, rdir.buf)) {
508 ret = error_errno("could not symlink '%s' to '%s'", wtdir.buf, rdir.buf);
513 if (stat(wtdir.buf, &st))
515 if (copy_file(rdir.buf, wtdir.buf,
517 ret = error("could not copy '%s' to '%s'", wtdir.buf, rdir.buf);
527 if (finish_command(&child)) {
528 ret = error("error occurred running diff --raw");
536 * Changes to submodules require special treatment.This loop writes a
537 * temporary file to both the left and right directories to show the
538 * change in the recorded SHA1 for the submodule.
540 hashmap_iter_init(&submodules, &iter);
541 while ((entry = hashmap_iter_next(&iter))) {
543 add_path(&ldir, ldir_len, entry->path);
544 ensure_leading_directories(ldir.buf);
545 write_file(ldir.buf, "%s", entry->left);
548 add_path(&rdir, rdir_len, entry->path);
549 ensure_leading_directories(rdir.buf);
550 write_file(rdir.buf, "%s", entry->right);
555 * Symbolic links require special treatment.The standard "git diff"
556 * shows only the link itself, not the contents of the link target.
557 * This loop replicates that behavior.
559 hashmap_iter_init(&symlinks2, &iter);
560 while ((entry = hashmap_iter_next(&iter))) {
562 add_path(&ldir, ldir_len, entry->path);
563 ensure_leading_directories(ldir.buf);
564 write_file(ldir.buf, "%s", entry->left);
567 add_path(&rdir, rdir_len, entry->path);
568 ensure_leading_directories(rdir.buf);
569 write_file(rdir.buf, "%s", entry->right);
573 strbuf_release(&buf);
575 strbuf_setlen(&ldir, ldir_len);
576 helper_argv[1] = ldir.buf;
577 strbuf_setlen(&rdir, rdir_len);
578 helper_argv[2] = rdir.buf;
581 helper_argv[0] = extcmd;
584 setenv("GIT_DIFFTOOL_DIRDIFF", "true", 1);
585 rc = run_command_v_opt(helper_argv, flags);
588 * If the diff includes working copy files and those
589 * files were modified during the diff, then the changes
590 * should be copied back to the working tree.
591 * Do not copy back files when symlinks are used and the
592 * external tool did not replace the original link with a file.
594 * These hashes are loaded lazily since they aren't needed
595 * in the common case of --symlinks and the difftool updating
596 * files through the symlink.
598 hashmap_init(&wt_modified, path_entry_cmp, NULL, wtindex.cache_nr);
599 hashmap_init(&tmp_modified, path_entry_cmp, NULL, wtindex.cache_nr);
601 for (i = 0; i < wtindex.cache_nr; i++) {
602 struct hashmap_entry dummy;
603 const char *name = wtindex.cache[i]->name;
606 add_path(&rdir, rdir_len, name);
607 if (lstat(rdir.buf, &st))
610 if ((symlinks && S_ISLNK(st.st_mode)) || !S_ISREG(st.st_mode))
613 if (!indices_loaded) {
614 struct lock_file lock = LOCK_INIT;
616 strbuf_addf(&buf, "%s/wtindex", tmpdir);
617 if (hold_lock_file_for_update(&lock, buf.buf, 0) < 0 ||
618 write_locked_index(&wtindex, &lock, COMMIT_LOCK)) {
619 ret = error("could not write %s", buf.buf);
622 changed_files(&wt_modified, buf.buf, workdir);
623 strbuf_setlen(&rdir, rdir_len);
624 changed_files(&tmp_modified, buf.buf, rdir.buf);
625 add_path(&rdir, rdir_len, name);
629 hashmap_entry_init(&dummy, strhash(name));
630 if (hashmap_get(&tmp_modified, &dummy, name)) {
631 add_path(&wtdir, wtdir_len, name);
632 if (hashmap_get(&wt_modified, &dummy, name)) {
633 warning(_("both files modified: '%s' and '%s'."),
634 wtdir.buf, rdir.buf);
635 warning(_("working tree file has been left."));
638 } else if (unlink(wtdir.buf) ||
639 copy_file(wtdir.buf, rdir.buf, st.st_mode))
640 warning_errno(_("could not copy '%s' to '%s'"),
641 rdir.buf, wtdir.buf);
646 warning(_("temporary files exist in '%s'."), tmpdir);
647 warning(_("you may want to cleanup or recover these."));
650 exit_cleanup(tmpdir, rc);
658 strbuf_release(&ldir);
659 strbuf_release(&rdir);
660 strbuf_release(&wtdir);
661 strbuf_release(&buf);
666 static int run_file_diff(int prompt, const char *prefix,
667 int argc, const char **argv)
669 struct argv_array args = ARGV_ARRAY_INIT;
670 const char *env[] = {
671 "GIT_PAGER=", "GIT_EXTERNAL_DIFF=git-difftool--helper", NULL,
677 env[2] = "GIT_DIFFTOOL_PROMPT=true";
679 env[2] = "GIT_DIFFTOOL_NO_PROMPT=true";
682 argv_array_push(&args, "diff");
683 for (i = 0; i < argc; i++)
684 argv_array_push(&args, argv[i]);
685 ret = run_command_v_opt_cd_env(args.argv, RUN_GIT_CMD, prefix, env);
689 int cmd_difftool(int argc, const char **argv, const char *prefix)
691 int use_gui_tool = 0, dir_diff = 0, prompt = -1, symlinks = 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"),
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 "
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")),
719 git_config(difftool_config, NULL);
720 symlinks = has_symlinks;
722 argc = parse_options(argc, argv, prefix, builtin_difftool_options,
723 builtin_difftool_usage, PARSE_OPT_KEEP_UNKNOWN |
724 PARSE_OPT_KEEP_DASHDASH);
727 return print_tool_help();
729 /* NEEDSWORK: once we no longer spawn anything, remove this */
730 setenv(GIT_DIR_ENVIRONMENT, absolute_path(get_git_dir()), 1);
731 setenv(GIT_WORK_TREE_ENVIRONMENT, absolute_path(get_git_work_tree()), 1);
733 if (use_gui_tool && diff_gui_tool && *diff_gui_tool)
734 setenv("GIT_DIFF_TOOL", diff_gui_tool, 1);
735 else if (difftool_cmd) {
737 setenv("GIT_DIFF_TOOL", difftool_cmd, 1);
739 die(_("no <tool> given for --tool=<tool>"));
744 setenv("GIT_DIFFTOOL_EXTCMD", extcmd, 1);
746 die(_("no <cmd> given for --extcmd=<cmd>"));
749 setenv("GIT_DIFFTOOL_TRUST_EXIT_CODE",
750 trust_exit_code ? "true" : "false", 1);
753 * In directory diff mode, 'git-difftool--helper' is called once
754 * to compare the a / b directories. In file diff mode, 'git diff'
755 * will invoke a separate instance of 'git-difftool--helper' for
756 * each file that changed.
759 return run_dir_diff(extcmd, symlinks, prefix, argc, argv);
760 return run_file_diff(prompt, prefix, argc, argv);