pre-receive.sample: mark it executable
[git/debian.git] / git-difftool.perl
blobebd13baa6e06cf7007fdd5c48713f06cf511721d
1 #!/usr/bin/perl
2 # Copyright (c) 2009, 2010 David Aguilar
3 # Copyright (c) 2012 Tim Henigan
5 # This is a wrapper around the GIT_EXTERNAL_DIFF-compatible
6 # git-difftool--helper script.
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.
11 # Any arguments that are unknown to this script are forwarded to 'git diff'.
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;
26 sub usage
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);
40 sub find_worktree
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');
48 sub print_tool_help
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));
56 sub exit_cleanup
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";
65 exit($status | ($status >> 8));
68 sub use_wt_file
70 my ($repo, $workdir, $file, $sha1) = @_;
71 my $null_sha1 = '0' x 40;
73 if (-l "$workdir/$file" || ! -e _) {
74 return (0, $null_sha1);
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);
82 sub changed_files
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;
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 {};
99 my $line = Git::command_oneline(@gitargs);
100 my @files;
101 if (defined $line) {
102 @files = split('\0', $line);
103 } else {
104 @files = ();
107 delete($ENV{GIT_INDEX_FILE});
108 delete($ENV{GIT_WORK_TREE});
109 delete($ENV{GIT_DIR}) if ($must_unset_git_dir);
111 return map { $_ => 1 } @files;
114 sub setup_dir_diff
116 my ($repo, $workdir, $symlinks) = @_;
118 # Run the diff; exit immediately if no diff found
119 # 'Repository' and 'WorkingCopy' must be explicitly set to insure that
120 # if $GIT_DIR and $GIT_WORK_TREE are set in ENV, they are actually used
121 # by Git->repository->command*.
122 my $repo_path = $repo->repo_path();
123 my %repo_args = (Repository => $repo_path, WorkingCopy => $workdir);
124 my $diffrepo = Git->repository(%repo_args);
126 my @gitargs = ('diff', '--raw', '--no-abbrev', '-z', @ARGV);
127 my $diffrtn = $diffrepo->command_oneline(@gitargs);
128 exit(0) unless defined($diffrtn);
130 # Build index info for left and right sides of the diff
131 my $submodule_mode = '160000';
132 my $symlink_mode = '120000';
133 my $null_mode = '0' x 6;
134 my $null_sha1 = '0' x 40;
135 my $lindex = '';
136 my $rindex = '';
137 my $wtindex = '';
138 my %submodule;
139 my %symlink;
140 my @working_tree = ();
141 my %working_tree_dups = ();
142 my @rawdiff = split('\0', $diffrtn);
144 my $i = 0;
145 while ($i < $#rawdiff) {
146 if ($rawdiff[$i] =~ /^::/) {
147 warn << 'EOF';
148 Combined diff formats ('-c' and '--cc') are not supported in
149 directory diff mode ('-d' and '--dir-diff').
151 exit(1);
154 my ($lmode, $rmode, $lsha1, $rsha1, $status) =
155 split(' ', substr($rawdiff[$i], 1));
156 my $src_path = $rawdiff[$i + 1];
157 my $dst_path;
159 if ($status =~ /^[CR]/) {
160 $dst_path = $rawdiff[$i + 2];
161 $i += 3;
162 } else {
163 $dst_path = $src_path;
164 $i += 2;
167 if ($lmode eq $submodule_mode or $rmode eq $submodule_mode) {
168 $submodule{$src_path}{left} = $lsha1;
169 if ($lsha1 ne $rsha1) {
170 $submodule{$dst_path}{right} = $rsha1;
171 } else {
172 $submodule{$dst_path}{right} = "$rsha1-dirty";
174 next;
177 if ($lmode eq $symlink_mode) {
178 $symlink{$src_path}{left} =
179 $diffrepo->command_oneline('show', "$lsha1");
182 if ($rmode eq $symlink_mode) {
183 $symlink{$dst_path}{right} =
184 $diffrepo->command_oneline('show', "$rsha1");
187 if ($lmode ne $null_mode and $status !~ /^C/) {
188 $lindex .= "$lmode $lsha1\t$src_path\0";
191 if ($rmode ne $null_mode) {
192 # Avoid duplicate working_tree entries
193 if ($working_tree_dups{$dst_path}++) {
194 next;
196 my ($use, $wt_sha1) = use_wt_file($repo, $workdir,
197 $dst_path, $rsha1);
198 if ($use) {
199 push @working_tree, $dst_path;
200 $wtindex .= "$rmode $wt_sha1\t$dst_path\0";
201 } else {
202 $rindex .= "$rmode $rsha1\t$dst_path\0";
207 # Setup temp directories
208 my $tmpdir = tempdir('git-difftool.XXXXX', CLEANUP => 0, TMPDIR => 1);
209 my $ldir = "$tmpdir/left";
210 my $rdir = "$tmpdir/right";
211 mkpath($ldir) or exit_cleanup($tmpdir, 1);
212 mkpath($rdir) or exit_cleanup($tmpdir, 1);
214 # If $GIT_DIR is not set prior to calling 'git update-index' and
215 # 'git checkout-index', then those commands will fail if difftool
216 # is called from a directory other than the repo root.
217 my $must_unset_git_dir = 0;
218 if (not defined($ENV{GIT_DIR})) {
219 $must_unset_git_dir = 1;
220 $ENV{GIT_DIR} = $repo_path;
223 # Populate the left and right directories based on each index file
224 my ($inpipe, $ctx);
225 $ENV{GIT_INDEX_FILE} = "$tmpdir/lindex";
226 ($inpipe, $ctx) =
227 $repo->command_input_pipe(qw(update-index -z --index-info));
228 print($inpipe $lindex);
229 $repo->command_close_pipe($inpipe, $ctx);
231 my $rc = system('git', 'checkout-index', '--all', "--prefix=$ldir/");
232 exit_cleanup($tmpdir, $rc) if $rc != 0;
234 $ENV{GIT_INDEX_FILE} = "$tmpdir/rindex";
235 ($inpipe, $ctx) =
236 $repo->command_input_pipe(qw(update-index -z --index-info));
237 print($inpipe $rindex);
238 $repo->command_close_pipe($inpipe, $ctx);
240 $rc = system('git', 'checkout-index', '--all', "--prefix=$rdir/");
241 exit_cleanup($tmpdir, $rc) if $rc != 0;
243 $ENV{GIT_INDEX_FILE} = "$tmpdir/wtindex";
244 ($inpipe, $ctx) =
245 $repo->command_input_pipe(qw(update-index --info-only -z --index-info));
246 print($inpipe $wtindex);
247 $repo->command_close_pipe($inpipe, $ctx);
249 # If $GIT_DIR was explicitly set just for the update/checkout
250 # commands, then it should be unset before continuing.
251 delete($ENV{GIT_DIR}) if ($must_unset_git_dir);
252 delete($ENV{GIT_INDEX_FILE});
254 # Changes in the working tree need special treatment since they are
255 # not part of the index. Remove any trailing slash from $workdir
256 # before starting to avoid double slashes in symlink targets.
257 $workdir =~ s|/$||;
258 for my $file (@working_tree) {
259 my $dir = dirname($file);
260 unless (-d "$rdir/$dir") {
261 mkpath("$rdir/$dir") or
262 exit_cleanup($tmpdir, 1);
264 if ($symlinks) {
265 symlink("$workdir/$file", "$rdir/$file") or
266 exit_cleanup($tmpdir, 1);
267 } else {
268 copy("$workdir/$file", "$rdir/$file") or
269 exit_cleanup($tmpdir, 1);
271 my $mode = stat("$workdir/$file")->mode;
272 chmod($mode, "$rdir/$file") or
273 exit_cleanup($tmpdir, 1);
277 # Changes to submodules require special treatment. This loop writes a
278 # temporary file to both the left and right directories to show the
279 # change in the recorded SHA1 for the submodule.
280 for my $path (keys %submodule) {
281 my $ok = 0;
282 if (defined($submodule{$path}{left})) {
283 $ok = write_to_file("$ldir/$path",
284 "Subproject commit $submodule{$path}{left}");
286 if (defined($submodule{$path}{right})) {
287 $ok = write_to_file("$rdir/$path",
288 "Subproject commit $submodule{$path}{right}");
290 exit_cleanup($tmpdir, 1) if not $ok;
293 # Symbolic links require special treatment. The standard "git diff"
294 # shows only the link itself, not the contents of the link target.
295 # This loop replicates that behavior.
296 for my $path (keys %symlink) {
297 my $ok = 0;
298 if (defined($symlink{$path}{left})) {
299 $ok = write_to_file("$ldir/$path",
300 $symlink{$path}{left});
302 if (defined($symlink{$path}{right})) {
303 $ok = write_to_file("$rdir/$path",
304 $symlink{$path}{right});
306 exit_cleanup($tmpdir, 1) if not $ok;
309 return ($ldir, $rdir, $tmpdir, @working_tree);
312 sub write_to_file
314 my $path = shift;
315 my $value = shift;
317 # Make sure the path to the file exists
318 my $dir = dirname($path);
319 unless (-d "$dir") {
320 mkpath("$dir") or return 0;
323 # If the file already exists in that location, delete it. This
324 # is required in the case of symbolic links.
325 unlink($path);
327 open(my $fh, '>', $path) or return 0;
328 print($fh $value);
329 close($fh);
331 return 1;
334 sub main
336 # parse command-line options. all unrecognized options and arguments
337 # are passed through to the 'git diff' command.
338 my %opts = (
339 difftool_cmd => undef,
340 dirdiff => undef,
341 extcmd => undef,
342 gui => undef,
343 help => undef,
344 prompt => undef,
345 symlinks => $^O ne 'cygwin' &&
346 $^O ne 'MSWin32' && $^O ne 'msys',
347 tool_help => undef,
348 trust_exit_code => undef,
350 GetOptions('g|gui!' => \$opts{gui},
351 'd|dir-diff' => \$opts{dirdiff},
352 'h' => \$opts{help},
353 'prompt!' => \$opts{prompt},
354 'y' => sub { $opts{prompt} = 0; },
355 'symlinks' => \$opts{symlinks},
356 'no-symlinks' => sub { $opts{symlinks} = 0; },
357 't|tool:s' => \$opts{difftool_cmd},
358 'tool-help' => \$opts{tool_help},
359 'trust-exit-code' => \$opts{trust_exit_code},
360 'no-trust-exit-code' => sub { $opts{trust_exit_code} = 0; },
361 'x|extcmd:s' => \$opts{extcmd});
363 if (defined($opts{help})) {
364 usage(0);
366 if (defined($opts{tool_help})) {
367 print_tool_help();
369 if (defined($opts{difftool_cmd})) {
370 if (length($opts{difftool_cmd}) > 0) {
371 $ENV{GIT_DIFF_TOOL} = $opts{difftool_cmd};
372 } else {
373 print "No <tool> given for --tool=<tool>\n";
374 usage(1);
377 if (defined($opts{extcmd})) {
378 if (length($opts{extcmd}) > 0) {
379 $ENV{GIT_DIFFTOOL_EXTCMD} = $opts{extcmd};
380 } else {
381 print "No <cmd> given for --extcmd=<cmd>\n";
382 usage(1);
385 if ($opts{gui}) {
386 my $guitool = Git::config('diff.guitool');
387 if (defined($guitool) && length($guitool) > 0) {
388 $ENV{GIT_DIFF_TOOL} = $guitool;
392 if (!defined $opts{trust_exit_code}) {
393 $opts{trust_exit_code} = Git::config_bool('difftool.trustExitCode');
395 if ($opts{trust_exit_code}) {
396 $ENV{GIT_DIFFTOOL_TRUST_EXIT_CODE} = 'true';
397 } else {
398 $ENV{GIT_DIFFTOOL_TRUST_EXIT_CODE} = 'false';
401 # In directory diff mode, 'git-difftool--helper' is called once
402 # to compare the a/b directories. In file diff mode, 'git diff'
403 # will invoke a separate instance of 'git-difftool--helper' for
404 # each file that changed.
405 if (defined($opts{dirdiff})) {
406 dir_diff($opts{extcmd}, $opts{symlinks});
407 } else {
408 file_diff($opts{prompt});
412 sub dir_diff
414 my ($extcmd, $symlinks) = @_;
415 my $rc;
416 my $error = 0;
417 my $repo = Git->repository();
418 my $workdir = find_worktree();
419 my ($a, $b, $tmpdir, @worktree) =
420 setup_dir_diff($repo, $workdir, $symlinks);
422 if (defined($extcmd)) {
423 $rc = system($extcmd, $a, $b);
424 } else {
425 $ENV{GIT_DIFFTOOL_DIRDIFF} = 'true';
426 $rc = system('git', 'difftool--helper', $a, $b);
428 # If the diff including working copy files and those
429 # files were modified during the diff, then the changes
430 # should be copied back to the working tree.
431 # Do not copy back files when symlinks are used and the
432 # external tool did not replace the original link with a file.
434 # These hashes are loaded lazily since they aren't needed
435 # in the common case of --symlinks and the difftool updating
436 # files through the symlink.
437 my %wt_modified;
438 my %tmp_modified;
439 my $indices_loaded = 0;
441 for my $file (@worktree) {
442 next if $symlinks && -l "$b/$file";
443 next if ! -f "$b/$file";
445 if (!$indices_loaded) {
446 %wt_modified = changed_files($repo->repo_path(),
447 "$tmpdir/wtindex", "$workdir");
448 %tmp_modified = changed_files($repo->repo_path(),
449 "$tmpdir/wtindex", "$b");
450 $indices_loaded = 1;
453 if (exists $wt_modified{$file} and exists $tmp_modified{$file}) {
454 my $errmsg = "warning: Both files modified: ";
455 $errmsg .= "'$workdir/$file' and '$b/$file'.\n";
456 $errmsg .= "warning: Working tree file has been left.\n";
457 $errmsg .= "warning:\n";
458 warn $errmsg;
459 $error = 1;
460 } elsif (exists $tmp_modified{$file}) {
461 my $mode = stat("$b/$file")->mode;
462 copy("$b/$file", "$workdir/$file") or
463 exit_cleanup($tmpdir, 1);
465 chmod($mode, "$workdir/$file") or
466 exit_cleanup($tmpdir, 1);
469 if ($error) {
470 warn "warning: Temporary files exist in '$tmpdir'.\n";
471 warn "warning: You may want to cleanup or recover these.\n";
472 exit(1);
473 } else {
474 exit_cleanup($tmpdir, $rc);
478 sub file_diff
480 my ($prompt) = @_;
482 if (defined($prompt)) {
483 if ($prompt) {
484 $ENV{GIT_DIFFTOOL_PROMPT} = 'true';
485 } else {
486 $ENV{GIT_DIFFTOOL_NO_PROMPT} = 'true';
490 $ENV{GIT_PAGER} = '';
491 $ENV{GIT_EXTERNAL_DIFF} = 'git-difftool--helper';
493 # ActiveState Perl for Win32 does not implement POSIX semantics of
494 # exec* system call. It just spawns the given executable and finishes
495 # the starting program, exiting with code 0.
496 # system will at least catch the errors returned by git diff,
497 # allowing the caller of git difftool better handling of failures.
498 my $rc = system('git', 'diff', @ARGV);
499 exit($rc | ($rc >> 8));
502 main();