difftool: Eliminate global variables
[alt-git.git] / git-difftool.perl
blob41ba9323f8356cf7e9b3df97d24e76d0da89e7e6
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 File::Basename qw(basename dirname);
17 use File::Copy;
18 use File::Compare;
19 use File::stat;
20 use File::Path qw(mkpath);
21 use File::Temp qw(tempdir);
22 use Getopt::Long qw(:config pass_through);
23 use Git;
25 sub usage
27 my $exitcode = shift;
28 print << 'USAGE';
29 usage: git difftool [-t|--tool=<tool>] [--tool-help]
30 [-x|--extcmd=<cmd>]
31 [-g|--gui] [--no-gui]
32 [--prompt] [-y|--no-prompt]
33 [-d|--dir-diff]
34 ['git diff' options]
35 USAGE
36 exit($exitcode);
39 sub find_worktree
41 my ($repo) = @_;
43 # Git->repository->wc_path() does not honor changes to the working
44 # tree location made by $ENV{GIT_WORK_TREE} or the 'core.worktree'
45 # config variable.
46 my $worktree;
47 my $env_worktree = $ENV{GIT_WORK_TREE};
48 my $core_worktree = Git::config('core.worktree');
50 if (defined($env_worktree) and (length($env_worktree) > 0)) {
51 $worktree = $env_worktree;
52 } elsif (defined($core_worktree) and (length($core_worktree) > 0)) {
53 $worktree = $core_worktree;
54 } else {
55 $worktree = $repo->wc_path();
58 return $worktree;
61 sub print_tool_help
63 my ($cmd, @found, @notfound);
64 my $gitpath = Git::exec_path();
66 my @files = map { basename($_) } glob("$gitpath/mergetools/*");
67 my @tools = sort(grep { !m{^defaults$} } @files);
69 foreach my $tool (@tools) {
70 $cmd = "TOOL_MODE=diff";
71 $cmd .= ' && . "$(git --exec-path)/git-mergetool--lib"';
72 $cmd .= " && get_merge_tool_path $tool >/dev/null 2>&1";
73 $cmd .= " && can_diff >/dev/null 2>&1";
74 if (system('sh', '-c', $cmd) == 0) {
75 push(@found, $tool);
76 } else {
77 push(@notfound, $tool);
81 print "'git difftool --tool=<tool>' may be set to one of the following:\n";
82 print "\t$_\n" for (@found);
84 print "\nThe following tools are valid, but not currently available:\n";
85 print "\t$_\n" for (@notfound);
87 print "\nNOTE: Some of the tools listed above only work in a windowed\n";
88 print "environment. If run in a terminal-only session, they will fail.\n";
90 exit(0);
93 sub setup_dir_diff
95 my ($repo, $workdir) = @_;
97 # Run the diff; exit immediately if no diff found
98 # 'Repository' and 'WorkingCopy' must be explicitly set to insure that
99 # if $GIT_DIR and $GIT_WORK_TREE are set in ENV, they are actually used
100 # by Git->repository->command*.
101 my $repo_path = $repo->repo_path();
102 my $diffrepo = Git->repository(Repository => $repo_path, WorkingCopy => $workdir);
103 my $diffrtn = $diffrepo->command_oneline('diff', '--raw', '--no-abbrev', '-z', @ARGV);
104 exit(0) if (length($diffrtn) == 0);
106 # Setup temp directories
107 my $tmpdir = tempdir('git-diffall.XXXXX', CLEANUP => 1, TMPDIR => 1);
108 my $ldir = "$tmpdir/left";
109 my $rdir = "$tmpdir/right";
110 mkpath($ldir) or die $!;
111 mkpath($rdir) or die $!;
113 # Build index info for left and right sides of the diff
114 my $submodule_mode = '160000';
115 my $symlink_mode = '120000';
116 my $null_mode = '0' x 6;
117 my $null_sha1 = '0' x 40;
118 my $lindex = '';
119 my $rindex = '';
120 my %submodule;
121 my %symlink;
122 my @working_tree = ();
123 my @rawdiff = split('\0', $diffrtn);
125 my $i = 0;
126 while ($i < $#rawdiff) {
127 if ($rawdiff[$i] =~ /^::/) {
128 print "Combined diff formats ('-c' and '--cc') are not supported in directory diff mode.\n";
129 exit(1);
132 my ($lmode, $rmode, $lsha1, $rsha1, $status) = split(' ', substr($rawdiff[$i], 1));
133 my $src_path = $rawdiff[$i + 1];
134 my $dst_path;
136 if ($status =~ /^[CR]/) {
137 $dst_path = $rawdiff[$i + 2];
138 $i += 3;
139 } else {
140 $dst_path = $src_path;
141 $i += 2;
144 if (($lmode eq $submodule_mode) or ($rmode eq $submodule_mode)) {
145 $submodule{$src_path}{left} = $lsha1;
146 if ($lsha1 ne $rsha1) {
147 $submodule{$dst_path}{right} = $rsha1;
148 } else {
149 $submodule{$dst_path}{right} = "$rsha1-dirty";
151 next;
154 if ($lmode eq $symlink_mode) {
155 $symlink{$src_path}{left} = $diffrepo->command_oneline('show', "$lsha1");
158 if ($rmode eq $symlink_mode) {
159 $symlink{$dst_path}{right} = $diffrepo->command_oneline('show', "$rsha1");
162 if (($lmode ne $null_mode) and ($status !~ /^C/)) {
163 $lindex .= "$lmode $lsha1\t$src_path\0";
166 if ($rmode ne $null_mode) {
167 if ($rsha1 ne $null_sha1) {
168 $rindex .= "$rmode $rsha1\t$dst_path\0";
169 } else {
170 push(@working_tree, $dst_path);
175 # If $GIT_DIR is not set prior to calling 'git update-index' and
176 # 'git checkout-index', then those commands will fail if difftool
177 # is called from a directory other than the repo root.
178 my $must_unset_git_dir = 0;
179 if (not defined($ENV{GIT_DIR})) {
180 $must_unset_git_dir = 1;
181 $ENV{GIT_DIR} = $repo_path;
184 # Populate the left and right directories based on each index file
185 my ($inpipe, $ctx);
186 $ENV{GIT_INDEX_FILE} = "$tmpdir/lindex";
187 ($inpipe, $ctx) = $repo->command_input_pipe(qw/update-index -z --index-info/);
188 print($inpipe $lindex);
189 $repo->command_close_pipe($inpipe, $ctx);
190 my $rc = system('git', 'checkout-index', '--all', "--prefix=$ldir/");
191 exit($rc | ($rc >> 8)) if ($rc != 0);
193 $ENV{GIT_INDEX_FILE} = "$tmpdir/rindex";
194 ($inpipe, $ctx) = $repo->command_input_pipe(qw/update-index -z --index-info/);
195 print($inpipe $rindex);
196 $repo->command_close_pipe($inpipe, $ctx);
197 $rc = system('git', 'checkout-index', '--all', "--prefix=$rdir/");
198 exit($rc | ($rc >> 8)) if ($rc != 0);
200 # If $GIT_DIR was explicitly set just for the update/checkout
201 # commands, then it should be unset before continuing.
202 delete($ENV{GIT_DIR}) if ($must_unset_git_dir);
203 delete($ENV{GIT_INDEX_FILE});
205 # Changes in the working tree need special treatment since they are
206 # not part of the index
207 for my $file (@working_tree) {
208 my $dir = dirname($file);
209 unless (-d "$rdir/$dir") {
210 mkpath("$rdir/$dir") or die $!;
212 copy("$workdir/$file", "$rdir/$file") or die $!;
213 chmod(stat("$workdir/$file")->mode, "$rdir/$file") or die $!;
216 # Changes to submodules require special treatment. This loop writes a
217 # temporary file to both the left and right directories to show the
218 # change in the recorded SHA1 for the submodule.
219 for my $path (keys %submodule) {
220 if (defined($submodule{$path}{left})) {
221 write_to_file("$ldir/$path", "Subproject commit $submodule{$path}{left}");
223 if (defined($submodule{$path}{right})) {
224 write_to_file("$rdir/$path", "Subproject commit $submodule{$path}{right}");
228 # Symbolic links require special treatment. The standard "git diff"
229 # shows only the link itself, not the contents of the link target.
230 # This loop replicates that behavior.
231 for my $path (keys %symlink) {
232 if (defined($symlink{$path}{left})) {
233 write_to_file("$ldir/$path", $symlink{$path}{left});
235 if (defined($symlink{$path}{right})) {
236 write_to_file("$rdir/$path", $symlink{$path}{right});
240 return ($ldir, $rdir, @working_tree);
243 sub write_to_file
245 my $path = shift;
246 my $value = shift;
248 # Make sure the path to the file exists
249 my $dir = dirname($path);
250 unless (-d "$dir") {
251 mkpath("$dir") or die $!;
254 # If the file already exists in that location, delete it. This
255 # is required in the case of symbolic links.
256 unlink("$path");
258 open(my $fh, '>', "$path") or die $!;
259 print($fh $value);
260 close($fh);
263 sub main
265 # parse command-line options. all unrecognized options and arguments
266 # are passed through to the 'git diff' command.
267 my ($difftool_cmd, $dirdiff, $extcmd, $gui, $help, $prompt, $tool_help);
268 GetOptions('g|gui!' => \$gui,
269 'd|dir-diff' => \$dirdiff,
270 'h' => \$help,
271 'prompt!' => \$prompt,
272 'y' => sub { $prompt = 0; },
273 't|tool:s' => \$difftool_cmd,
274 'tool-help' => \$tool_help,
275 'x|extcmd:s' => \$extcmd);
277 if (defined($help)) {
278 usage(0);
280 if (defined($tool_help)) {
281 print_tool_help();
283 if (defined($difftool_cmd)) {
284 if (length($difftool_cmd) > 0) {
285 $ENV{GIT_DIFF_TOOL} = $difftool_cmd;
286 } else {
287 print "No <tool> given for --tool=<tool>\n";
288 usage(1);
291 if (defined($extcmd)) {
292 if (length($extcmd) > 0) {
293 $ENV{GIT_DIFFTOOL_EXTCMD} = $extcmd;
294 } else {
295 print "No <cmd> given for --extcmd=<cmd>\n";
296 usage(1);
299 if ($gui) {
300 my $guitool = '';
301 $guitool = Git::config('diff.guitool');
302 if (length($guitool) > 0) {
303 $ENV{GIT_DIFF_TOOL} = $guitool;
307 # In directory diff mode, 'git-difftool--helper' is called once
308 # to compare the a/b directories. In file diff mode, 'git diff'
309 # will invoke a separate instance of 'git-difftool--helper' for
310 # each file that changed.
311 if (defined($dirdiff)) {
312 dir_diff($extcmd);
313 } else {
314 file_diff($prompt);
318 sub dir_diff
320 my ($extcmd) = @_;
322 my $rc;
323 my $repo = Git->repository();
325 my $workdir = find_worktree($repo);
326 my ($a, $b, @working_tree) = setup_dir_diff($repo, $workdir);
327 if (defined($extcmd)) {
328 $rc = system($extcmd, $a, $b);
329 } else {
330 $ENV{GIT_DIFFTOOL_DIRDIFF} = 'true';
331 $rc = system('git', 'difftool--helper', $a, $b);
334 exit($rc | ($rc >> 8)) if ($rc != 0);
336 # If the diff including working copy files and those
337 # files were modified during the diff, then the changes
338 # should be copied back to the working tree
339 for my $file (@working_tree) {
340 if (-e "$b/$file" && compare("$b/$file", "$workdir/$file")) {
341 copy("$b/$file", "$workdir/$file") or die $!;
342 chmod(stat("$b/$file")->mode, "$workdir/$file") or die $!;
347 sub file_diff
349 my ($prompt) = @_;
351 if (defined($prompt)) {
352 if ($prompt) {
353 $ENV{GIT_DIFFTOOL_PROMPT} = 'true';
354 } else {
355 $ENV{GIT_DIFFTOOL_NO_PROMPT} = 'true';
359 $ENV{GIT_PAGER} = '';
360 $ENV{GIT_EXTERNAL_DIFF} = 'git-difftool--helper';
362 # ActiveState Perl for Win32 does not implement POSIX semantics of
363 # exec* system call. It just spawns the given executable and finishes
364 # the starting program, exiting with code 0.
365 # system will at least catch the errors returned by git diff,
366 # allowing the caller of git difftool better handling of failures.
367 my $rc = system('git', 'diff', @ARGV);
368 exit($rc | ($rc >> 8));
371 main();