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