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