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