difftool: fix argument handling in subdirs
[git] / git-difftool.perl
1 #!/usr/bin/perl
2 # Copyright (c) 2009, 2010 David Aguilar
3 # Copyright (c) 2012 Tim Henigan
4 #
5 # This is a wrapper around the GIT_EXTERNAL_DIFF-compatible
6 # git-difftool--helper script.
7 #
8 # This script exports GIT_EXTERNAL_DIFF and GIT_PAGER for use by git.
9 # The GIT_DIFF* variables are exported for use by git-difftool--helper.
10 #
11 # Any arguments that are unknown to this script are forwarded to 'git diff'.
12
13 use 5.008;
14 use strict;
15 use warnings;
16 use Error qw(:try);
17 use File::Basename qw(dirname);
18 use File::Copy;
19 use File::Find;
20 use File::stat;
21 use File::Path qw(mkpath rmtree);
22 use File::Temp qw(tempdir);
23 use Getopt::Long qw(:config pass_through);
24 use Git;
25
26 sub usage
27 {
28         my $exitcode = shift;
29         print << 'USAGE';
30 usage: git difftool [-t|--tool=<tool>] [--tool-help]
31                     [-x|--extcmd=<cmd>]
32                     [-g|--gui] [--no-gui]
33                     [--prompt] [-y|--no-prompt]
34                     [-d|--dir-diff]
35                     ['git diff' options]
36 USAGE
37         exit($exitcode);
38 }
39
40 sub find_worktree
41 {
42         # Git->repository->wc_path() does not honor changes to the working
43         # tree location made by $ENV{GIT_WORK_TREE} or the 'core.worktree'
44         # config variable.
45         return Git::command_oneline('rev-parse', '--show-toplevel');
46 }
47
48 sub print_tool_help
49 {
50         # See the comment at the bottom of file_diff() for the reason behind
51         # using system() followed by exit() instead of exec().
52         my $rc = system(qw(git mergetool --tool-help=diff));
53         exit($rc | ($rc >> 8));
54 }
55
56 sub exit_cleanup
57 {
58         my ($tmpdir, $status) = @_;
59         my $errno = $!;
60         rmtree($tmpdir);
61         if ($status and $errno) {
62                 my ($package, $file, $line) = caller();
63                 warn "$file line $line: $errno\n";
64         }
65         exit($status | ($status >> 8));
66 }
67
68 sub use_wt_file
69 {
70         my ($repo, $workdir, $file, $sha1) = @_;
71         my $null_sha1 = '0' x 40;
72
73         if (-l "$workdir/$file" || ! -e _) {
74                 return (0, $null_sha1);
75         }
76
77         my $wt_sha1 = $repo->command_oneline('hash-object', "$workdir/$file");
78         my $use = ($sha1 eq $null_sha1) || ($sha1 eq $wt_sha1);
79         return ($use, $wt_sha1);
80 }
81
82 sub changed_files
83 {
84         my ($repo_path, $index, $worktree) = @_;
85         $ENV{GIT_INDEX_FILE} = $index;
86         $ENV{GIT_WORK_TREE} = $worktree;
87         my $must_unset_git_dir = 0;
88         if (not defined($ENV{GIT_DIR})) {
89                 $must_unset_git_dir = 1;
90                 $ENV{GIT_DIR} = $repo_path;
91         }
92
93         my @refreshargs = qw/update-index --really-refresh -q --unmerged/;
94         my @gitargs = qw/diff-files --name-only -z/;
95         try {
96                 Git::command_oneline(@refreshargs);
97         } catch Git::Error::Command with {};
98
99         my $line = Git::command_oneline(@gitargs);
100         my @files;
101         if (defined $line) {
102                 @files = split('\0', $line);
103         } else {
104                 @files = ();
105         }
106
107         delete($ENV{GIT_INDEX_FILE});
108         delete($ENV{GIT_WORK_TREE});
109         delete($ENV{GIT_DIR}) if ($must_unset_git_dir);
110
111         return map { $_ => 1 } @files;
112 }
113
114 sub setup_dir_diff
115 {
116         my ($repo, $workdir, $symlinks) = @_;
117
118         my $repo_path = $repo->repo_path();
119         my @gitargs = ('diff', '--raw', '--no-abbrev', '-z', @ARGV);
120         my $diffrtn = $repo->command_oneline(@gitargs);
121         exit(0) unless defined($diffrtn);
122
123         # Build index info for left and right sides of the diff
124         my $submodule_mode = '160000';
125         my $symlink_mode = '120000';
126         my $null_mode = '0' x 6;
127         my $null_sha1 = '0' x 40;
128         my $lindex = '';
129         my $rindex = '';
130         my $wtindex = '';
131         my %submodule;
132         my %symlink;
133         my @working_tree = ();
134         my %working_tree_dups = ();
135         my @rawdiff = split('\0', $diffrtn);
136
137         my $i = 0;
138         while ($i < $#rawdiff) {
139                 if ($rawdiff[$i] =~ /^::/) {
140                         warn << 'EOF';
141 Combined diff formats ('-c' and '--cc') are not supported in
142 directory diff mode ('-d' and '--dir-diff').
143 EOF
144                         exit(1);
145                 }
146
147                 my ($lmode, $rmode, $lsha1, $rsha1, $status) =
148                         split(' ', substr($rawdiff[$i], 1));
149                 my $src_path = $rawdiff[$i + 1];
150                 my $dst_path;
151
152                 if ($status =~ /^[CR]/) {
153                         $dst_path = $rawdiff[$i + 2];
154                         $i += 3;
155                 } else {
156                         $dst_path = $src_path;
157                         $i += 2;
158                 }
159
160                 if ($lmode eq $submodule_mode or $rmode eq $submodule_mode) {
161                         $submodule{$src_path}{left} = $lsha1;
162                         if ($lsha1 ne $rsha1) {
163                                 $submodule{$dst_path}{right} = $rsha1;
164                         } else {
165                                 $submodule{$dst_path}{right} = "$rsha1-dirty";
166                         }
167                         next;
168                 }
169
170                 if ($lmode eq $symlink_mode) {
171                         $symlink{$src_path}{left} =
172                                 $repo->command_oneline('show', "$lsha1");
173                 }
174
175                 if ($rmode eq $symlink_mode) {
176                         $symlink{$dst_path}{right} =
177                                 $repo->command_oneline('show', "$rsha1");
178                 }
179
180                 if ($lmode ne $null_mode and $status !~ /^C/) {
181                         $lindex .= "$lmode $lsha1\t$src_path\0";
182                 }
183
184                 if ($rmode ne $null_mode) {
185                         # Avoid duplicate working_tree entries
186                         if ($working_tree_dups{$dst_path}++) {
187                                 next;
188                         }
189                         my ($use, $wt_sha1) = use_wt_file($repo, $workdir,
190                                                           $dst_path, $rsha1);
191                         if ($use) {
192                                 push @working_tree, $dst_path;
193                                 $wtindex .= "$rmode $wt_sha1\t$dst_path\0";
194                         } else {
195                                 $rindex .= "$rmode $rsha1\t$dst_path\0";
196                         }
197                 }
198         }
199
200         # Setup temp directories
201         my $tmpdir = tempdir('git-difftool.XXXXX', CLEANUP => 0, TMPDIR => 1);
202         my $ldir = "$tmpdir/left";
203         my $rdir = "$tmpdir/right";
204         mkpath($ldir) or exit_cleanup($tmpdir, 1);
205         mkpath($rdir) or exit_cleanup($tmpdir, 1);
206
207         # If $GIT_DIR is not set prior to calling 'git update-index' and
208         # 'git checkout-index', then those commands will fail if difftool
209         # is called from a directory other than the repo root.
210         my $must_unset_git_dir = 0;
211         if (not defined($ENV{GIT_DIR})) {
212                 $must_unset_git_dir = 1;
213                 $ENV{GIT_DIR} = $repo_path;
214         }
215
216         # Populate the left and right directories based on each index file
217         my ($inpipe, $ctx);
218         $ENV{GIT_INDEX_FILE} = "$tmpdir/lindex";
219         ($inpipe, $ctx) =
220                 $repo->command_input_pipe(qw(update-index -z --index-info));
221         print($inpipe $lindex);
222         $repo->command_close_pipe($inpipe, $ctx);
223
224         my $rc = system('git', 'checkout-index', '--all', "--prefix=$ldir/");
225         exit_cleanup($tmpdir, $rc) if $rc != 0;
226
227         $ENV{GIT_INDEX_FILE} = "$tmpdir/rindex";
228         ($inpipe, $ctx) =
229                 $repo->command_input_pipe(qw(update-index -z --index-info));
230         print($inpipe $rindex);
231         $repo->command_close_pipe($inpipe, $ctx);
232
233         $rc = system('git', 'checkout-index', '--all', "--prefix=$rdir/");
234         exit_cleanup($tmpdir, $rc) if $rc != 0;
235
236         $ENV{GIT_INDEX_FILE} = "$tmpdir/wtindex";
237         ($inpipe, $ctx) =
238                 $repo->command_input_pipe(qw(update-index --info-only -z --index-info));
239         print($inpipe $wtindex);
240         $repo->command_close_pipe($inpipe, $ctx);
241
242         # If $GIT_DIR was explicitly set just for the update/checkout
243         # commands, then it should be unset before continuing.
244         delete($ENV{GIT_DIR}) if ($must_unset_git_dir);
245         delete($ENV{GIT_INDEX_FILE});
246
247         # Changes in the working tree need special treatment since they are
248         # not part of the index. Remove any trailing slash from $workdir
249         # before starting to avoid double slashes in symlink targets.
250         $workdir =~ s|/$||;
251         for my $file (@working_tree) {
252                 my $dir = dirname($file);
253                 unless (-d "$rdir/$dir") {
254                         mkpath("$rdir/$dir") or
255                         exit_cleanup($tmpdir, 1);
256                 }
257                 if ($symlinks) {
258                         symlink("$workdir/$file", "$rdir/$file") or
259                         exit_cleanup($tmpdir, 1);
260                 } else {
261                         copy("$workdir/$file", "$rdir/$file") or
262                         exit_cleanup($tmpdir, 1);
263
264                         my $mode = stat("$workdir/$file")->mode;
265                         chmod($mode, "$rdir/$file") or
266                         exit_cleanup($tmpdir, 1);
267                 }
268         }
269
270         # Changes to submodules require special treatment. This loop writes a
271         # temporary file to both the left and right directories to show the
272         # change in the recorded SHA1 for the submodule.
273         for my $path (keys %submodule) {
274                 my $ok = 0;
275                 if (defined($submodule{$path}{left})) {
276                         $ok = write_to_file("$ldir/$path",
277                                 "Subproject commit $submodule{$path}{left}");
278                 }
279                 if (defined($submodule{$path}{right})) {
280                         $ok = write_to_file("$rdir/$path",
281                                 "Subproject commit $submodule{$path}{right}");
282                 }
283                 exit_cleanup($tmpdir, 1) if not $ok;
284         }
285
286         # Symbolic links require special treatment. The standard "git diff"
287         # shows only the link itself, not the contents of the link target.
288         # This loop replicates that behavior.
289         for my $path (keys %symlink) {
290                 my $ok = 0;
291                 if (defined($symlink{$path}{left})) {
292                         $ok = write_to_file("$ldir/$path",
293                                         $symlink{$path}{left});
294                 }
295                 if (defined($symlink{$path}{right})) {
296                         $ok = write_to_file("$rdir/$path",
297                                         $symlink{$path}{right});
298                 }
299                 exit_cleanup($tmpdir, 1) if not $ok;
300         }
301
302         return ($ldir, $rdir, $tmpdir, @working_tree);
303 }
304
305 sub write_to_file
306 {
307         my $path = shift;
308         my $value = shift;
309
310         # Make sure the path to the file exists
311         my $dir = dirname($path);
312         unless (-d "$dir") {
313                 mkpath("$dir") or return 0;
314         }
315
316         # If the file already exists in that location, delete it.  This
317         # is required in the case of symbolic links.
318         unlink($path);
319
320         open(my $fh, '>', $path) or return 0;
321         print($fh $value);
322         close($fh);
323
324         return 1;
325 }
326
327 sub main
328 {
329         # parse command-line options. all unrecognized options and arguments
330         # are passed through to the 'git diff' command.
331         my %opts = (
332                 difftool_cmd => undef,
333                 dirdiff => undef,
334                 extcmd => undef,
335                 gui => undef,
336                 help => undef,
337                 prompt => undef,
338                 symlinks => $^O ne 'cygwin' &&
339                                 $^O ne 'MSWin32' && $^O ne 'msys',
340                 tool_help => undef,
341                 trust_exit_code => undef,
342         );
343         GetOptions('g|gui!' => \$opts{gui},
344                 'd|dir-diff' => \$opts{dirdiff},
345                 'h' => \$opts{help},
346                 'prompt!' => \$opts{prompt},
347                 'y' => sub { $opts{prompt} = 0; },
348                 'symlinks' => \$opts{symlinks},
349                 'no-symlinks' => sub { $opts{symlinks} = 0; },
350                 't|tool:s' => \$opts{difftool_cmd},
351                 'tool-help' => \$opts{tool_help},
352                 'trust-exit-code' => \$opts{trust_exit_code},
353                 'no-trust-exit-code' => sub { $opts{trust_exit_code} = 0; },
354                 'x|extcmd:s' => \$opts{extcmd});
355
356         if (defined($opts{help})) {
357                 usage(0);
358         }
359         if (defined($opts{tool_help})) {
360                 print_tool_help();
361         }
362         if (defined($opts{difftool_cmd})) {
363                 if (length($opts{difftool_cmd}) > 0) {
364                         $ENV{GIT_DIFF_TOOL} = $opts{difftool_cmd};
365                 } else {
366                         print "No <tool> given for --tool=<tool>\n";
367                         usage(1);
368                 }
369         }
370         if (defined($opts{extcmd})) {
371                 if (length($opts{extcmd}) > 0) {
372                         $ENV{GIT_DIFFTOOL_EXTCMD} = $opts{extcmd};
373                 } else {
374                         print "No <cmd> given for --extcmd=<cmd>\n";
375                         usage(1);
376                 }
377         }
378         if ($opts{gui}) {
379                 my $guitool = Git::config('diff.guitool');
380                 if (defined($guitool) && length($guitool) > 0) {
381                         $ENV{GIT_DIFF_TOOL} = $guitool;
382                 }
383         }
384
385         if (!defined $opts{trust_exit_code}) {
386                 $opts{trust_exit_code} = Git::config_bool('difftool.trustExitCode');
387         }
388         if ($opts{trust_exit_code}) {
389                 $ENV{GIT_DIFFTOOL_TRUST_EXIT_CODE} = 'true';
390         } else {
391                 $ENV{GIT_DIFFTOOL_TRUST_EXIT_CODE} = 'false';
392         }
393
394         # In directory diff mode, 'git-difftool--helper' is called once
395         # to compare the a/b directories.  In file diff mode, 'git diff'
396         # will invoke a separate instance of 'git-difftool--helper' for
397         # each file that changed.
398         if (defined($opts{dirdiff})) {
399                 dir_diff($opts{extcmd}, $opts{symlinks});
400         } else {
401                 file_diff($opts{prompt});
402         }
403 }
404
405 sub dir_diff
406 {
407         my ($extcmd, $symlinks) = @_;
408         my $rc;
409         my $error = 0;
410         my $repo = Git->repository();
411         my $workdir = find_worktree();
412         my ($a, $b, $tmpdir, @worktree) =
413                 setup_dir_diff($repo, $workdir, $symlinks);
414
415         if (defined($extcmd)) {
416                 $rc = system($extcmd, $a, $b);
417         } else {
418                 $ENV{GIT_DIFFTOOL_DIRDIFF} = 'true';
419                 $rc = system('git', 'difftool--helper', $a, $b);
420         }
421         # If the diff including working copy files and those
422         # files were modified during the diff, then the changes
423         # should be copied back to the working tree.
424         # Do not copy back files when symlinks are used and the
425         # external tool did not replace the original link with a file.
426         #
427         # These hashes are loaded lazily since they aren't needed
428         # in the common case of --symlinks and the difftool updating
429         # files through the symlink.
430         my %wt_modified;
431         my %tmp_modified;
432         my $indices_loaded = 0;
433
434         for my $file (@worktree) {
435                 next if $symlinks && -l "$b/$file";
436                 next if ! -f "$b/$file";
437
438                 if (!$indices_loaded) {
439                         %wt_modified = changed_files($repo->repo_path(),
440                                 "$tmpdir/wtindex", "$workdir");
441                         %tmp_modified = changed_files($repo->repo_path(),
442                                 "$tmpdir/wtindex", "$b");
443                         $indices_loaded = 1;
444                 }
445
446                 if (exists $wt_modified{$file} and exists $tmp_modified{$file}) {
447                         my $errmsg = "warning: Both files modified: ";
448                         $errmsg .= "'$workdir/$file' and '$b/$file'.\n";
449                         $errmsg .= "warning: Working tree file has been left.\n";
450                         $errmsg .= "warning:\n";
451                         warn $errmsg;
452                         $error = 1;
453                 } elsif (exists $tmp_modified{$file}) {
454                         my $mode = stat("$b/$file")->mode;
455                         copy("$b/$file", "$workdir/$file") or
456                         exit_cleanup($tmpdir, 1);
457
458                         chmod($mode, "$workdir/$file") or
459                         exit_cleanup($tmpdir, 1);
460                 }
461         }
462         if ($error) {
463                 warn "warning: Temporary files exist in '$tmpdir'.\n";
464                 warn "warning: You may want to cleanup or recover these.\n";
465                 exit(1);
466         } else {
467                 exit_cleanup($tmpdir, $rc);
468         }
469 }
470
471 sub file_diff
472 {
473         my ($prompt) = @_;
474
475         if (defined($prompt)) {
476                 if ($prompt) {
477                         $ENV{GIT_DIFFTOOL_PROMPT} = 'true';
478                 } else {
479                         $ENV{GIT_DIFFTOOL_NO_PROMPT} = 'true';
480                 }
481         }
482
483         $ENV{GIT_PAGER} = '';
484         $ENV{GIT_EXTERNAL_DIFF} = 'git-difftool--helper';
485
486         # ActiveState Perl for Win32 does not implement POSIX semantics of
487         # exec* system call. It just spawns the given executable and finishes
488         # the starting program, exiting with code 0.
489         # system will at least catch the errors returned by git diff,
490         # allowing the caller of git difftool better handling of failures.
491         my $rc = system('git', 'diff', @ARGV);
492         exit($rc | ($rc >> 8));
493 }
494
495 main();