compat/unsetenv.c: Fix a sparse warning
[alt-git.git] / git-difftool.perl
blob67802922ccc41fa2993c1bce4ea1a3d2899c7a40
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 my ($repo) = @_;
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');
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();
59 return $worktree;
62 sub print_tool_help
64 my $cmd = 'TOOL_MODE=diff';
65 $cmd .= ' && . "$(git --exec-path)/git-mergetool--lib"';
66 $cmd .= ' && show_tool_help';
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));
74 sub exit_cleanup
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";
83 exit($status | ($status >> 8));
86 sub use_wt_file
88 my ($repo, $workdir, $file, $sha1, $symlinks) = @_;
89 my $null_sha1 = '0' x 40;
91 if ($sha1 ne $null_sha1 and not $symlinks) {
92 return 0;
95 my $wt_sha1 = $repo->command_oneline('hash-object', "$workdir/$file");
96 my $use = ($sha1 eq $null_sha1) || ($sha1 eq $wt_sha1);
97 return ($use, $wt_sha1);
100 sub changed_files
102 my ($repo_path, $index, $worktree) = @_;
103 $ENV{GIT_INDEX_FILE} = $index;
104 $ENV{GIT_WORK_TREE} = $worktree;
105 my $must_unset_git_dir = 0;
106 if (not defined($ENV{GIT_DIR})) {
107 $must_unset_git_dir = 1;
108 $ENV{GIT_DIR} = $repo_path;
111 my @refreshargs = qw/update-index --really-refresh -q --unmerged/;
112 my @gitargs = qw/diff-files --name-only -z/;
113 try {
114 Git::command_oneline(@refreshargs);
115 } catch Git::Error::Command with {};
117 my $line = Git::command_oneline(@gitargs);
118 my @files;
119 if (defined $line) {
120 @files = split('\0', $line);
121 } else {
122 @files = ();
125 delete($ENV{GIT_INDEX_FILE});
126 delete($ENV{GIT_WORK_TREE});
127 delete($ENV{GIT_DIR}) if ($must_unset_git_dir);
129 return map { $_ => 1 } @files;
132 sub setup_dir_diff
134 my ($repo, $workdir, $symlinks) = @_;
136 # Run the diff; exit immediately if no diff found
137 # 'Repository' and 'WorkingCopy' must be explicitly set to insure that
138 # if $GIT_DIR and $GIT_WORK_TREE are set in ENV, they are actually used
139 # by Git->repository->command*.
140 my $repo_path = $repo->repo_path();
141 my %repo_args = (Repository => $repo_path, WorkingCopy => $workdir);
142 my $diffrepo = Git->repository(%repo_args);
144 my @gitargs = ('diff', '--raw', '--no-abbrev', '-z', @ARGV);
145 my $diffrtn = $diffrepo->command_oneline(@gitargs);
146 exit(0) unless defined($diffrtn);
148 # Build index info for left and right sides of the diff
149 my $submodule_mode = '160000';
150 my $symlink_mode = '120000';
151 my $null_mode = '0' x 6;
152 my $null_sha1 = '0' x 40;
153 my $lindex = '';
154 my $rindex = '';
155 my $wtindex = '';
156 my %submodule;
157 my %symlink;
158 my @working_tree = ();
159 my @rawdiff = split('\0', $diffrtn);
161 my $i = 0;
162 while ($i < $#rawdiff) {
163 if ($rawdiff[$i] =~ /^::/) {
164 warn << 'EOF';
165 Combined diff formats ('-c' and '--cc') are not supported in
166 directory diff mode ('-d' and '--dir-diff').
168 exit(1);
171 my ($lmode, $rmode, $lsha1, $rsha1, $status) =
172 split(' ', substr($rawdiff[$i], 1));
173 my $src_path = $rawdiff[$i + 1];
174 my $dst_path;
176 if ($status =~ /^[CR]/) {
177 $dst_path = $rawdiff[$i + 2];
178 $i += 3;
179 } else {
180 $dst_path = $src_path;
181 $i += 2;
184 if ($lmode eq $submodule_mode or $rmode eq $submodule_mode) {
185 $submodule{$src_path}{left} = $lsha1;
186 if ($lsha1 ne $rsha1) {
187 $submodule{$dst_path}{right} = $rsha1;
188 } else {
189 $submodule{$dst_path}{right} = "$rsha1-dirty";
191 next;
194 if ($lmode eq $symlink_mode) {
195 $symlink{$src_path}{left} =
196 $diffrepo->command_oneline('show', "$lsha1");
199 if ($rmode eq $symlink_mode) {
200 $symlink{$dst_path}{right} =
201 $diffrepo->command_oneline('show', "$rsha1");
204 if ($lmode ne $null_mode and $status !~ /^C/) {
205 $lindex .= "$lmode $lsha1\t$src_path\0";
208 if ($rmode ne $null_mode) {
209 my ($use, $wt_sha1) = use_wt_file($repo, $workdir,
210 $dst_path, $rsha1,
211 $symlinks);
212 if ($use) {
213 push @working_tree, $dst_path;
214 $wtindex .= "$rmode $wt_sha1\t$dst_path\0";
215 } else {
216 $rindex .= "$rmode $rsha1\t$dst_path\0";
221 # Setup temp directories
222 my $tmpdir = tempdir('git-difftool.XXXXX', CLEANUP => 0, TMPDIR => 1);
223 my $ldir = "$tmpdir/left";
224 my $rdir = "$tmpdir/right";
225 mkpath($ldir) or exit_cleanup($tmpdir, 1);
226 mkpath($rdir) or exit_cleanup($tmpdir, 1);
228 # If $GIT_DIR is not set prior to calling 'git update-index' and
229 # 'git checkout-index', then those commands will fail if difftool
230 # is called from a directory other than the repo root.
231 my $must_unset_git_dir = 0;
232 if (not defined($ENV{GIT_DIR})) {
233 $must_unset_git_dir = 1;
234 $ENV{GIT_DIR} = $repo_path;
237 # Populate the left and right directories based on each index file
238 my ($inpipe, $ctx);
239 $ENV{GIT_INDEX_FILE} = "$tmpdir/lindex";
240 ($inpipe, $ctx) =
241 $repo->command_input_pipe(qw(update-index -z --index-info));
242 print($inpipe $lindex);
243 $repo->command_close_pipe($inpipe, $ctx);
245 my $rc = system('git', 'checkout-index', '--all', "--prefix=$ldir/");
246 exit_cleanup($tmpdir, $rc) if $rc != 0;
248 $ENV{GIT_INDEX_FILE} = "$tmpdir/rindex";
249 ($inpipe, $ctx) =
250 $repo->command_input_pipe(qw(update-index -z --index-info));
251 print($inpipe $rindex);
252 $repo->command_close_pipe($inpipe, $ctx);
254 $rc = system('git', 'checkout-index', '--all', "--prefix=$rdir/");
255 exit_cleanup($tmpdir, $rc) if $rc != 0;
257 $ENV{GIT_INDEX_FILE} = "$tmpdir/wtindex";
258 ($inpipe, $ctx) =
259 $repo->command_input_pipe(qw(update-index --info-only -z --index-info));
260 print($inpipe $wtindex);
261 $repo->command_close_pipe($inpipe, $ctx);
263 # If $GIT_DIR was explicitly set just for the update/checkout
264 # commands, then it should be unset before continuing.
265 delete($ENV{GIT_DIR}) if ($must_unset_git_dir);
266 delete($ENV{GIT_INDEX_FILE});
268 # Changes in the working tree need special treatment since they are
269 # not part of the index. Remove any trailing slash from $workdir
270 # before starting to avoid double slashes in symlink targets.
271 $workdir =~ s|/$||;
272 for my $file (@working_tree) {
273 my $dir = dirname($file);
274 unless (-d "$rdir/$dir") {
275 mkpath("$rdir/$dir") or
276 exit_cleanup($tmpdir, 1);
278 if ($symlinks) {
279 symlink("$workdir/$file", "$rdir/$file") or
280 exit_cleanup($tmpdir, 1);
281 } else {
282 copy("$workdir/$file", "$rdir/$file") or
283 exit_cleanup($tmpdir, 1);
285 my $mode = stat("$workdir/$file")->mode;
286 chmod($mode, "$rdir/$file") or
287 exit_cleanup($tmpdir, 1);
291 # Changes to submodules require special treatment. This loop writes a
292 # temporary file to both the left and right directories to show the
293 # change in the recorded SHA1 for the submodule.
294 for my $path (keys %submodule) {
295 my $ok;
296 if (defined($submodule{$path}{left})) {
297 $ok = write_to_file("$ldir/$path",
298 "Subproject commit $submodule{$path}{left}");
300 if (defined($submodule{$path}{right})) {
301 $ok = write_to_file("$rdir/$path",
302 "Subproject commit $submodule{$path}{right}");
304 exit_cleanup($tmpdir, 1) if not $ok;
307 # Symbolic links require special treatment. The standard "git diff"
308 # shows only the link itself, not the contents of the link target.
309 # This loop replicates that behavior.
310 for my $path (keys %symlink) {
311 my $ok;
312 if (defined($symlink{$path}{left})) {
313 $ok = write_to_file("$ldir/$path",
314 $symlink{$path}{left});
316 if (defined($symlink{$path}{right})) {
317 $ok = write_to_file("$rdir/$path",
318 $symlink{$path}{right});
320 exit_cleanup($tmpdir, 1) if not $ok;
323 return ($ldir, $rdir, $tmpdir, @working_tree);
326 sub write_to_file
328 my $path = shift;
329 my $value = shift;
331 # Make sure the path to the file exists
332 my $dir = dirname($path);
333 unless (-d "$dir") {
334 mkpath("$dir") or return 0;
337 # If the file already exists in that location, delete it. This
338 # is required in the case of symbolic links.
339 unlink($path);
341 open(my $fh, '>', $path) or return 0;
342 print($fh $value);
343 close($fh);
345 return 1;
348 sub main
350 # parse command-line options. all unrecognized options and arguments
351 # are passed through to the 'git diff' command.
352 my %opts = (
353 difftool_cmd => undef,
354 dirdiff => undef,
355 extcmd => undef,
356 gui => undef,
357 help => undef,
358 prompt => undef,
359 symlinks => $^O ne 'cygwin' &&
360 $^O ne 'MSWin32' && $^O ne 'msys',
361 tool_help => undef,
363 GetOptions('g|gui!' => \$opts{gui},
364 'd|dir-diff' => \$opts{dirdiff},
365 'h' => \$opts{help},
366 'prompt!' => \$opts{prompt},
367 'y' => sub { $opts{prompt} = 0; },
368 'symlinks' => \$opts{symlinks},
369 'no-symlinks' => sub { $opts{symlinks} = 0; },
370 't|tool:s' => \$opts{difftool_cmd},
371 'tool-help' => \$opts{tool_help},
372 'x|extcmd:s' => \$opts{extcmd});
374 if (defined($opts{help})) {
375 usage(0);
377 if (defined($opts{tool_help})) {
378 print_tool_help();
380 if (defined($opts{difftool_cmd})) {
381 if (length($opts{difftool_cmd}) > 0) {
382 $ENV{GIT_DIFF_TOOL} = $opts{difftool_cmd};
383 } else {
384 print "No <tool> given for --tool=<tool>\n";
385 usage(1);
388 if (defined($opts{extcmd})) {
389 if (length($opts{extcmd}) > 0) {
390 $ENV{GIT_DIFFTOOL_EXTCMD} = $opts{extcmd};
391 } else {
392 print "No <cmd> given for --extcmd=<cmd>\n";
393 usage(1);
396 if ($opts{gui}) {
397 my $guitool = Git::config('diff.guitool');
398 if (defined($guitool) && length($guitool) > 0) {
399 $ENV{GIT_DIFF_TOOL} = $guitool;
403 # In directory diff mode, 'git-difftool--helper' is called once
404 # to compare the a/b directories. In file diff mode, 'git diff'
405 # will invoke a separate instance of 'git-difftool--helper' for
406 # each file that changed.
407 if (defined($opts{dirdiff})) {
408 dir_diff($opts{extcmd}, $opts{symlinks});
409 } else {
410 file_diff($opts{prompt});
414 sub dir_diff
416 my ($extcmd, $symlinks) = @_;
417 my $rc;
418 my $error = 0;
419 my $repo = Git->repository();
420 my $workdir = find_worktree($repo);
421 my ($a, $b, $tmpdir, @worktree) =
422 setup_dir_diff($repo, $workdir, $symlinks);
424 if (defined($extcmd)) {
425 $rc = system($extcmd, $a, $b);
426 } else {
427 $ENV{GIT_DIFFTOOL_DIRDIFF} = 'true';
428 $rc = system('git', 'difftool--helper', $a, $b);
430 # If the diff including working copy files and those
431 # files were modified during the diff, then the changes
432 # should be copied back to the working tree.
433 # Do not copy back files when symlinks are used and the
434 # external tool did not replace the original link with a file.
436 # These hashes are loaded lazily since they aren't needed
437 # in the common case of --symlinks and the difftool updating
438 # files through the symlink.
439 my %wt_modified;
440 my %tmp_modified;
441 my $indices_loaded = 0;
443 for my $file (@worktree) {
444 next if $symlinks && -l "$b/$file";
445 next if ! -f "$b/$file";
447 if (!$indices_loaded) {
448 %wt_modified = changed_files($repo->repo_path(),
449 "$tmpdir/wtindex", "$workdir");
450 %tmp_modified = changed_files($repo->repo_path(),
451 "$tmpdir/wtindex", "$b");
452 $indices_loaded = 1;
455 if (exists $wt_modified{$file} and exists $tmp_modified{$file}) {
456 my $errmsg = "warning: Both files modified: ";
457 $errmsg .= "'$workdir/$file' and '$b/$file'.\n";
458 $errmsg .= "warning: Working tree file has been left.\n";
459 $errmsg .= "warning:\n";
460 warn $errmsg;
461 $error = 1;
462 } elsif (exists $tmp_modified{$file}) {
463 my $mode = stat("$b/$file")->mode;
464 copy("$b/$file", "$workdir/$file") or
465 exit_cleanup($tmpdir, 1);
467 chmod($mode, "$workdir/$file") or
468 exit_cleanup($tmpdir, 1);
471 if ($error) {
472 warn "warning: Temporary files exist in '$tmpdir'.\n";
473 warn "warning: You may want to cleanup or recover these.\n";
474 exit(1);
475 } else {
476 exit_cleanup($tmpdir, $rc);
480 sub file_diff
482 my ($prompt) = @_;
484 if (defined($prompt)) {
485 if ($prompt) {
486 $ENV{GIT_DIFFTOOL_PROMPT} = 'true';
487 } else {
488 $ENV{GIT_DIFFTOOL_NO_PROMPT} = 'true';
492 $ENV{GIT_PAGER} = '';
493 $ENV{GIT_EXTERNAL_DIFF} = 'git-difftool--helper';
495 # ActiveState Perl for Win32 does not implement POSIX semantics of
496 # exec* system call. It just spawns the given executable and finishes
497 # the starting program, exiting with code 0.
498 # system will at least catch the errors returned by git diff,
499 # allowing the caller of git difftool better handling of failures.
500 my $rc = system('git', 'diff', @ARGV);
501 exit($rc | ($rc >> 8));
504 main();