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