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, 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,
135 const void *entry_or_key,
136 const void *unused_keydata)
138 const struct working_tree_entry *a = entry;
139 const struct working_tree_entry *b = entry_or_key;
140 return strcmp(a->path, b->path);
144 * The `left` and `right` entries hold paths for the symlinks hashmap,
145 * and a SHA-1 surrounded by brief text for submodules.
148 struct hashmap_entry entry;
149 char left[PATH_MAX], right[PATH_MAX];
150 const char path[FLEX_ARRAY];
153 static int pair_cmp(const void *unused_cmp_data,
155 const void *entry_or_key,
156 const void *unused_keydata)
158 const struct pair_entry *a = entry;
159 const struct pair_entry *b = entry_or_key;
161 return strcmp(a->path, b->path);
164 static void add_left_or_right(struct hashmap *map, const char *path,
165 const char *content, int is_right)
167 struct pair_entry *e, *existing;
169 FLEX_ALLOC_STR(e, path, path);
170 hashmap_entry_init(e, strhash(path));
171 existing = hashmap_get(map, e, NULL);
176 e->left[0] = e->right[0] = '\0';
179 strlcpy(is_right ? e->right : e->left, content, PATH_MAX);
183 struct hashmap_entry entry;
184 char path[FLEX_ARRAY];
187 static int path_entry_cmp(const void *unused_cmp_data,
189 const void *entry_or_key,
192 const struct path_entry *a = entry;
193 const struct path_entry *b = entry_or_key;
195 return strcmp(a->path, key ? key : b->path);
198 static void changed_files(struct hashmap *result, const char *index_path,
201 struct child_process update_index = CHILD_PROCESS_INIT;
202 struct child_process diff_files = CHILD_PROCESS_INIT;
203 struct strbuf index_env = STRBUF_INIT, buf = STRBUF_INIT;
204 const char *git_dir = absolute_path(get_git_dir()), *env[] = {
209 strbuf_addf(&index_env, "GIT_INDEX_FILE=%s", index_path);
210 env[0] = index_env.buf;
212 argv_array_pushl(&update_index.args,
213 "--git-dir", git_dir, "--work-tree", workdir,
214 "update-index", "--really-refresh", "-q",
216 update_index.no_stdin = 1;
217 update_index.no_stdout = 1;
218 update_index.no_stderr = 1;
219 update_index.git_cmd = 1;
220 update_index.use_shell = 0;
221 update_index.clean_on_exit = 1;
222 update_index.dir = workdir;
223 update_index.env = env;
224 /* Ignore any errors of update-index */
225 run_command(&update_index);
227 argv_array_pushl(&diff_files.args,
228 "--git-dir", git_dir, "--work-tree", workdir,
229 "diff-files", "--name-only", "-z", NULL);
230 diff_files.no_stdin = 1;
231 diff_files.git_cmd = 1;
232 diff_files.use_shell = 0;
233 diff_files.clean_on_exit = 1;
235 diff_files.dir = workdir;
236 diff_files.env = env;
237 if (start_command(&diff_files))
238 die("could not obtain raw diff");
239 fp = xfdopen(diff_files.out, "r");
240 while (!strbuf_getline_nul(&buf, fp)) {
241 struct path_entry *entry;
242 FLEX_ALLOC_STR(entry, path, buf.buf);
243 hashmap_entry_init(entry, strhash(buf.buf));
244 hashmap_add(result, entry);
247 if (finish_command(&diff_files))
248 die("diff-files did not exit properly");
249 strbuf_release(&index_env);
250 strbuf_release(&buf);
253 static NORETURN void exit_cleanup(const char *tmpdir, int exit_code)
255 struct strbuf buf = STRBUF_INIT;
256 strbuf_addstr(&buf, tmpdir);
257 remove_dir_recursively(&buf, 0);
259 warning(_("failed: %d"), exit_code);
263 static int ensure_leading_directories(char *path)
265 switch (safe_create_leading_directories(path)) {
270 return error(_("could not create leading directories "
276 * Unconditional writing of a plain regular file is what
277 * "git difftool --dir-diff" wants to do for symlinks. We are preparing two
278 * temporary directories to be fed to a Git-unaware tool that knows how to
279 * show a diff of two directories (e.g. "diff -r A B").
281 * Because the tool is Git-unaware, if a symbolic link appears in either of
282 * these temporary directories, it will try to dereference and show the
283 * difference of the target of the symbolic link, which is not what we want,
284 * as the goal of the dir-diff mode is to produce an output that is logically
285 * equivalent to what "git diff" produces.
287 * Most importantly, we want to get textual comparison of the result of the
288 * readlink(2). get_symlink() provides that---it returns the contents of
289 * the symlink that gets written to a regular file to force the external tool
290 * to compare the readlink(2) result as text, even on a filesystem that is
291 * capable of doing a symbolic link.
293 static char *get_symlink(const struct object_id *oid, const char *path)
296 if (is_null_oid(oid)) {
297 /* The symlink is unknown to Git so read from the filesystem */
298 struct strbuf link = STRBUF_INIT;
300 if (strbuf_readlink(&link, path, strlen(path)))
301 die(_("could not read symlink %s"), path);
302 } else if (strbuf_read_file(&link, path, 128))
303 die(_("could not read symlink file %s"), path);
305 data = strbuf_detach(&link, NULL);
307 enum object_type type;
309 data = read_object_file(oid, &type, &size);
311 die(_("could not read object %s for symlink %s"),
312 oid_to_hex(oid), path);
318 static int checkout_path(unsigned mode, struct object_id *oid,
319 const char *path, const struct checkout *state)
321 struct cache_entry *ce;
324 ce = make_cache_entry(mode, oid->hash, path, 0, 0);
325 ret = checkout_entry(ce, state, NULL);
331 static int run_dir_diff(const char *extcmd, int symlinks, const char *prefix,
332 int argc, const char **argv)
334 char tmpdir[PATH_MAX];
335 struct strbuf info = STRBUF_INIT, lpath = STRBUF_INIT;
336 struct strbuf rpath = STRBUF_INIT, buf = STRBUF_INIT;
337 struct strbuf ldir = STRBUF_INIT, rdir = STRBUF_INIT;
338 struct strbuf wtdir = STRBUF_INIT;
339 char *lbase_dir, *rbase_dir;
340 size_t ldir_len, rdir_len, wtdir_len;
341 const char *workdir, *tmp;
344 struct hashmap working_tree_dups, submodules, symlinks2;
345 struct hashmap_iter iter;
346 struct pair_entry *entry;
347 struct index_state wtindex;
348 struct checkout lstate, rstate;
349 int rc, flags = RUN_GIT_CMD, err = 0;
350 struct child_process child = CHILD_PROCESS_INIT;
351 const char *helper_argv[] = { "difftool--helper", NULL, NULL, NULL };
352 struct hashmap wt_modified, tmp_modified;
353 int indices_loaded = 0;
355 workdir = get_git_work_tree();
357 /* Setup temp directories */
358 tmp = getenv("TMPDIR");
359 xsnprintf(tmpdir, sizeof(tmpdir), "%s/git-difftool.XXXXXX", tmp ? tmp : "/tmp");
360 if (!mkdtemp(tmpdir))
361 return error("could not create '%s'", tmpdir);
362 strbuf_addf(&ldir, "%s/left/", tmpdir);
363 strbuf_addf(&rdir, "%s/right/", tmpdir);
364 strbuf_addstr(&wtdir, workdir);
365 if (!wtdir.len || !is_dir_sep(wtdir.buf[wtdir.len - 1]))
366 strbuf_addch(&wtdir, '/');
367 mkdir(ldir.buf, 0700);
368 mkdir(rdir.buf, 0700);
370 memset(&wtindex, 0, sizeof(wtindex));
372 memset(&lstate, 0, sizeof(lstate));
373 lstate.base_dir = lbase_dir = xstrdup(ldir.buf);
374 lstate.base_dir_len = ldir.len;
376 memset(&rstate, 0, sizeof(rstate));
377 rstate.base_dir = rbase_dir = xstrdup(rdir.buf);
378 rstate.base_dir_len = rdir.len;
383 wtdir_len = wtdir.len;
385 hashmap_init(&working_tree_dups, working_tree_entry_cmp, NULL, 0);
386 hashmap_init(&submodules, pair_cmp, NULL, 0);
387 hashmap_init(&symlinks2, pair_cmp, NULL, 0);
392 child.clean_on_exit = 1;
395 argv_array_pushl(&child.args, "diff", "--raw", "--no-abbrev", "-z",
397 for (i = 0; i < argc; i++)
398 argv_array_push(&child.args, argv[i]);
399 if (start_command(&child))
400 die("could not obtain raw diff");
401 fp = xfdopen(child.out, "r");
403 /* Build index info for left and right sides of the diff */
405 while (!strbuf_getline_nul(&info, fp)) {
407 struct object_id loid, roid;
409 const char *src_path, *dst_path;
411 if (starts_with(info.buf, "::"))
412 die(N_("combined diff formats('-c' and '--cc') are "
414 "directory diff mode('-d' and '--dir-diff')."));
416 if (parse_index_info(info.buf, &lmode, &rmode, &loid, &roid,
419 if (strbuf_getline_nul(&lpath, fp))
421 src_path = lpath.buf;
424 if (status != 'C' && status != 'R') {
427 if (strbuf_getline_nul(&rpath, fp))
429 dst_path = rpath.buf;
432 if (S_ISGITLINK(lmode) || S_ISGITLINK(rmode)) {
434 strbuf_addf(&buf, "Subproject commit %s",
436 add_left_or_right(&submodules, src_path, buf.buf, 0);
438 strbuf_addf(&buf, "Subproject commit %s",
440 if (!oidcmp(&loid, &roid))
441 strbuf_addstr(&buf, "-dirty");
442 add_left_or_right(&submodules, dst_path, buf.buf, 1);
446 if (S_ISLNK(lmode)) {
447 char *content = get_symlink(&loid, src_path);
448 add_left_or_right(&symlinks2, src_path, content, 0);
452 if (S_ISLNK(rmode)) {
453 char *content = get_symlink(&roid, dst_path);
454 add_left_or_right(&symlinks2, dst_path, content, 1);
458 if (lmode && status != 'C') {
459 if (checkout_path(lmode, &loid, src_path, &lstate)) {
460 ret = error("could not write '%s'", src_path);
465 if (rmode && !S_ISLNK(rmode)) {
466 struct working_tree_entry *entry;
468 /* Avoid duplicate working_tree entries */
469 FLEX_ALLOC_STR(entry, path, dst_path);
470 hashmap_entry_init(entry, strhash(dst_path));
471 if (hashmap_get(&working_tree_dups, entry, NULL)) {
475 hashmap_add(&working_tree_dups, entry);
477 if (!use_wt_file(workdir, dst_path, &roid)) {
478 if (checkout_path(rmode, &roid, dst_path,
480 ret = error("could not write '%s'",
484 } else if (!is_null_oid(&roid)) {
486 * Changes in the working tree need special
487 * treatment since they are not part of the
490 struct cache_entry *ce2 =
491 make_cache_entry(rmode, roid.hash,
494 add_index_entry(&wtindex, ce2,
495 ADD_CACHE_JUST_APPEND);
497 add_path(&rdir, rdir_len, dst_path);
498 if (ensure_leading_directories(rdir.buf)) {
499 ret = error("could not create "
500 "directory for '%s'",
504 add_path(&wtdir, wtdir_len, dst_path);
506 if (symlink(wtdir.buf, rdir.buf)) {
507 ret = error_errno("could not symlink '%s' to '%s'", wtdir.buf, rdir.buf);
512 if (stat(wtdir.buf, &st))
514 if (copy_file(rdir.buf, wtdir.buf,
516 ret = error("could not copy '%s' to '%s'", wtdir.buf, rdir.buf);
526 if (finish_command(&child)) {
527 ret = error("error occurred running diff --raw");
535 * Changes to submodules require special treatment.This loop writes a
536 * temporary file to both the left and right directories to show the
537 * change in the recorded SHA1 for the submodule.
539 hashmap_iter_init(&submodules, &iter);
540 while ((entry = hashmap_iter_next(&iter))) {
542 add_path(&ldir, ldir_len, entry->path);
543 ensure_leading_directories(ldir.buf);
544 write_file(ldir.buf, "%s", entry->left);
547 add_path(&rdir, rdir_len, entry->path);
548 ensure_leading_directories(rdir.buf);
549 write_file(rdir.buf, "%s", entry->right);
554 * Symbolic links require special treatment.The standard "git diff"
555 * shows only the link itself, not the contents of the link target.
556 * This loop replicates that behavior.
558 hashmap_iter_init(&symlinks2, &iter);
559 while ((entry = hashmap_iter_next(&iter))) {
561 add_path(&ldir, ldir_len, entry->path);
562 ensure_leading_directories(ldir.buf);
563 write_file(ldir.buf, "%s", entry->left);
566 add_path(&rdir, rdir_len, entry->path);
567 ensure_leading_directories(rdir.buf);
568 write_file(rdir.buf, "%s", entry->right);
572 strbuf_release(&buf);
574 strbuf_setlen(&ldir, ldir_len);
575 helper_argv[1] = ldir.buf;
576 strbuf_setlen(&rdir, rdir_len);
577 helper_argv[2] = rdir.buf;
580 helper_argv[0] = extcmd;
583 setenv("GIT_DIFFTOOL_DIRDIFF", "true", 1);
584 rc = run_command_v_opt(helper_argv, flags);
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.
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.
597 hashmap_init(&wt_modified, path_entry_cmp, NULL, wtindex.cache_nr);
598 hashmap_init(&tmp_modified, path_entry_cmp, NULL, wtindex.cache_nr);
600 for (i = 0; i < wtindex.cache_nr; i++) {
601 struct hashmap_entry dummy;
602 const char *name = wtindex.cache[i]->name;
605 add_path(&rdir, rdir_len, name);
606 if (lstat(rdir.buf, &st))
609 if ((symlinks && S_ISLNK(st.st_mode)) || !S_ISREG(st.st_mode))
612 if (!indices_loaded) {
613 struct lock_file lock = LOCK_INIT;
615 strbuf_addf(&buf, "%s/wtindex", tmpdir);
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);
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);
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."));
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);
645 warning(_("temporary files exist in '%s'."), tmpdir);
646 warning(_("you may want to cleanup or recover these."));
649 exit_cleanup(tmpdir, rc);
657 strbuf_release(&ldir);
658 strbuf_release(&rdir);
659 strbuf_release(&wtdir);
660 strbuf_release(&buf);
665 static int run_file_diff(int prompt, const char *prefix,
666 int argc, const char **argv)
668 struct argv_array args = ARGV_ARRAY_INIT;
669 const char *env[] = {
670 "GIT_PAGER=", "GIT_EXTERNAL_DIFF=git-difftool--helper", NULL,
676 env[2] = "GIT_DIFFTOOL_PROMPT=true";
678 env[2] = "GIT_DIFFTOOL_NO_PROMPT=true";
681 argv_array_push(&args, "diff");
682 for (i = 0; i < argc; i++)
683 argv_array_push(&args, argv[i]);
684 ret = run_command_v_opt_cd_env(args.argv, RUN_GIT_CMD, prefix, env);
688 int cmd_difftool(int argc, const char **argv, const char *prefix)
690 int use_gui_tool = 0, dir_diff = 0, prompt = -1, symlinks = 0,
692 static char *difftool_cmd = NULL, *extcmd = NULL;
693 struct option builtin_difftool_options[] = {
694 OPT_BOOL('g', "gui", &use_gui_tool,
695 N_("use `diff.guitool` instead of `diff.tool`")),
696 OPT_BOOL('d', "dir-diff", &dir_diff,
697 N_("perform a full-directory diff")),
698 OPT_SET_INT_F('y', "no-prompt", &prompt,
699 N_("do not prompt before launching a diff tool"),
701 OPT_SET_INT_F(0, "prompt", &prompt, NULL,
702 1, PARSE_OPT_NONEG | PARSE_OPT_HIDDEN),
703 OPT_BOOL(0, "symlinks", &symlinks,
704 N_("use symlinks in dir-diff mode")),
705 OPT_STRING('t', "tool", &difftool_cmd, N_("<tool>"),
706 N_("use the specified diff tool")),
707 OPT_BOOL(0, "tool-help", &tool_help,
708 N_("print a list of diff tools that may be used with "
710 OPT_BOOL(0, "trust-exit-code", &trust_exit_code,
711 N_("make 'git-difftool' exit when an invoked diff "
712 "tool returns a non - zero exit code")),
713 OPT_STRING('x', "extcmd", &extcmd, N_("<command>"),
714 N_("specify a custom command for viewing diffs")),
718 git_config(difftool_config, NULL);
719 symlinks = has_symlinks;
721 argc = parse_options(argc, argv, prefix, builtin_difftool_options,
722 builtin_difftool_usage, PARSE_OPT_KEEP_UNKNOWN |
723 PARSE_OPT_KEEP_DASHDASH);
726 return print_tool_help();
728 /* NEEDSWORK: once we no longer spawn anything, remove this */
729 setenv(GIT_DIR_ENVIRONMENT, absolute_path(get_git_dir()), 1);
730 setenv(GIT_WORK_TREE_ENVIRONMENT, absolute_path(get_git_work_tree()), 1);
732 if (use_gui_tool && diff_gui_tool && *diff_gui_tool)
733 setenv("GIT_DIFF_TOOL", diff_gui_tool, 1);
734 else if (difftool_cmd) {
736 setenv("GIT_DIFF_TOOL", difftool_cmd, 1);
738 die(_("no <tool> given for --tool=<tool>"));
743 setenv("GIT_DIFFTOOL_EXTCMD", extcmd, 1);
745 die(_("no <cmd> given for --extcmd=<cmd>"));
748 setenv("GIT_DIFFTOOL_TRUST_EXIT_CODE",
749 trust_exit_code ? "true" : "false", 1);
752 * In directory diff mode, 'git-difftool--helper' is called once
753 * to compare the a / b directories. In file diff mode, 'git diff'
754 * will invoke a separate instance of 'git-difftool--helper' for
755 * each file that changed.
758 return run_dir_diff(extcmd, symlinks, prefix, argc, argv);
759 return run_file_diff(prompt, prefix, argc, argv);