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