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