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