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