1=head1 NAME 2 3Git - Perl interface to the Git version control system 4 5=cut 6 7 8package Git; 9 10use5.008; 11use strict; 12use warnings; 13 14use File::Temp (); 15use File::Spec (); 16 17BEGIN{ 18 19our($VERSION,@ISA,@EXPORT,@EXPORT_OK); 20 21# Totally unstable API. 22$VERSION='0.01'; 23 24 25=head1 SYNOPSIS 26 27 use Git; 28 29 my $version = Git::command_oneline('version'); 30 31 git_cmd_try { Git::command_noisy('update-server-info') } 32 '%s failed w/ code %d'; 33 34 my $repo = Git->repository (Directory => '/srv/git/cogito.git'); 35 36 37 my @revs = $repo->command('rev-list', '--since=last monday', '--all'); 38 39 my ($fh, $c) = $repo->command_output_pipe('rev-list', '--since=last monday', '--all'); 40 my $lastrev = <$fh>; chomp $lastrev; 41 $repo->command_close_pipe($fh, $c); 42 43 my $lastrev = $repo->command_oneline( [ 'rev-list', '--all' ], 44 STDERR => 0 ); 45 46 my $sha1 = $repo->hash_and_insert_object('file.txt'); 47 my $tempfile = tempfile(); 48 my $size = $repo->cat_blob($sha1, $tempfile); 49 50=cut 51 52 53require Exporter; 54 55@ISA=qw(Exporter); 56 57@EXPORT=qw(git_cmd_try); 58 59# Methods which can be called as standalone functions as well: 60@EXPORT_OK=qw(command command_oneline command_noisy 61 command_output_pipe command_input_pipe command_close_pipe 62 command_bidi_pipe command_close_bidi_pipe 63 version exec_path html_path hash_object git_cmd_try 64 remote_refs prompt 65 get_tz_offset get_record 66 credential credential_read credential_write 67 temp_acquire temp_is_locked temp_release temp_reset temp_path 68 unquote_path); 69 70 71=head1 DESCRIPTION 72 73This module provides Perl scripts easy way to interface the Git version control 74system. The modules have an easy and well-tested way to call arbitrary Git 75commands; in the future, the interface will also provide specialized methods 76for doing easily operations which are not totally trivial to do over 77the generic command interface. 78 79While some commands can be executed outside of any context (e.g. 'version' 80or 'init'), most operations require a repository context, which in practice 81means getting an instance of the Git object using the repository() constructor. 82(In the future, we will also get a new_repository() constructor.) All commands 83called as methods of the object are then executed in the context of the 84repository. 85 86Part of the "repository state" is also information about path to the attached 87working copy (unless you work with a bare repository). You can also navigate 88inside of the working copy using the C<wc_chdir()> method. (Note that 89the repository object is self-contained and will not change working directory 90of your process.) 91 92TODO: In the future, we might also do 93 94 my $remoterepo = $repo->remote_repository (Name => 'cogito', Branch => 'master'); 95 $remoterepo ||= Git->remote_repository ('http://git.or.cz/cogito.git/'); 96 my @refs = $remoterepo->refs(); 97 98Currently, the module merely wraps calls to external Git tools. In the future, 99it will provide a much faster way to interact with Git by linking directly 100to libgit. This should be completely opaque to the user, though (performance 101increase notwithstanding). 102 103=cut 104 105 106use Carp qw(carp croak);# but croak is bad - throw instead 107use Git::LoadCPAN::Error qw(:try); 108use Cwd qw(abs_path cwd); 109use IPC::Open2 qw(open2); 110use Fcntl qw(SEEK_SET SEEK_CUR); 111use Time::Local qw(timegm); 112} 113 114 115=head1 CONSTRUCTORS 116 117=over 4 118 119=item repository ( OPTIONS ) 120 121=item repository ( DIRECTORY ) 122 123=item repository () 124 125Construct a new repository object. 126C<OPTIONS> are passed in a hash like fashion, using key and value pairs. 127Possible options are: 128 129B<Repository> - Path to the Git repository. 130 131B<WorkingCopy> - Path to the associated working copy; not strictly required 132as many commands will happily crunch on a bare repository. 133 134B<WorkingSubdir> - Subdirectory in the working copy to work inside. 135Just left undefined if you do not want to limit the scope of operations. 136 137B<Directory> - Path to the Git working directory in its usual setup. 138The C<.git> directory is searched in the directory and all the parent 139directories; if found, C<WorkingCopy> is set to the directory containing 140it and C<Repository> to the C<.git> directory itself. If no C<.git> 141directory was found, the C<Directory> is assumed to be a bare repository, 142C<Repository> is set to point at it and C<WorkingCopy> is left undefined. 143If the C<$GIT_DIR> environment variable is set, things behave as expected 144as well. 145 146You should not use both C<Directory> and either of C<Repository> and 147C<WorkingCopy> - the results of that are undefined. 148 149Alternatively, a directory path may be passed as a single scalar argument 150to the constructor; it is equivalent to setting only the C<Directory> option 151field. 152 153Calling the constructor with no options whatsoever is equivalent to 154calling it with C<< Directory => '.' >>. In general, if you are building 155a standard porcelain command, simply doing C<< Git->repository() >> should 156do the right thing and setup the object to reflect exactly where the user 157is right now. 158 159=cut 160 161sub repository { 162my$class=shift; 163my@args=@_; 164my%opts= (); 165my$self; 166 167if(defined$args[0]) { 168if($#args%2!=1) { 169# Not a hash. 170$#args==0or throw Error::Simple("bad usage"); 171%opts= ( Directory =>$args[0] ); 172}else{ 173%opts=@args; 174} 175} 176 177if(not defined$opts{Repository}and not defined$opts{WorkingCopy} 178and not defined$opts{Directory}) { 179$opts{Directory} ='.'; 180} 181 182if(defined$opts{Directory}) { 183-d $opts{Directory}or throw Error::Simple("Directory not found:$opts{Directory}$!"); 184 185my$search= Git->repository(WorkingCopy =>$opts{Directory}); 186my$dir; 187try{ 188$dir=$search->command_oneline(['rev-parse','--git-dir'], 189 STDERR =>0); 190} catch Git::Error::Command with { 191$dir=undef; 192}; 193 194if($dir) { 195 File::Spec->file_name_is_absolute($dir)or$dir=$opts{Directory} .'/'.$dir; 196$opts{Repository} = abs_path($dir); 197 198# If --git-dir went ok, this shouldn't die either. 199my$prefix=$search->command_oneline('rev-parse','--show-prefix'); 200$dir= abs_path($opts{Directory}) .'/'; 201if($prefix) { 202if(substr($dir, -length($prefix))ne$prefix) { 203 throw Error::Simple("rev-parse confused me -$dirdoes not have trailing$prefix"); 204} 205substr($dir, -length($prefix)) =''; 206} 207$opts{WorkingCopy} =$dir; 208$opts{WorkingSubdir} =$prefix; 209 210}else{ 211# A bare repository? Let's see... 212$dir=$opts{Directory}; 213 214unless(-d "$dir/refs"and-d "$dir/objects"and-e "$dir/HEAD") { 215# Mimic git-rev-parse --git-dir error message: 216 throw Error::Simple("fatal: Not a git repository:$dir"); 217} 218my$search= Git->repository(Repository =>$dir); 219try{ 220$search->command('symbolic-ref','HEAD'); 221} catch Git::Error::Command with { 222# Mimic git-rev-parse --git-dir error message: 223 throw Error::Simple("fatal: Not a git repository:$dir"); 224} 225 226$opts{Repository} = abs_path($dir); 227} 228 229delete$opts{Directory}; 230} 231 232$self= { opts => \%opts}; 233bless$self,$class; 234} 235 236=back 237 238=head1 METHODS 239 240=over 4 241 242=item command ( COMMAND [, ARGUMENTS... ] ) 243 244=item command ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } ) 245 246Execute the given Git C<COMMAND> (specify it without the 'git-' 247prefix), optionally with the specified extra C<ARGUMENTS>. 248 249The second more elaborate form can be used if you want to further adjust 250the command execution. Currently, only one option is supported: 251 252B<STDERR> - How to deal with the command's error output. By default (C<undef>) 253it is delivered to the caller's C<STDERR>. A false value (0 or '') will cause 254it to be thrown away. If you want to process it, you can get it in a filehandle 255you specify, but you must be extremely careful; if the error output is not 256very short and you want to read it in the same process as where you called 257C<command()>, you are set up for a nice deadlock! 258 259The method can be called without any instance or on a specified Git repository 260(in that case the command will be run in the repository context). 261 262In scalar context, it returns all the command output in a single string 263(verbatim). 264 265In array context, it returns an array containing lines printed to the 266command's stdout (without trailing newlines). 267 268In both cases, the command's stdin and stderr are the same as the caller's. 269 270=cut 271 272sub command { 273my($fh,$ctx) = command_output_pipe(@_); 274 275if(not defined wantarray) { 276# Nothing to pepper the possible exception with. 277 _cmd_close($ctx,$fh); 278 279}elsif(not wantarray) { 280local$/; 281my$text= <$fh>; 282try{ 283 _cmd_close($ctx,$fh); 284} catch Git::Error::Command with { 285# Pepper with the output: 286my$E=shift; 287$E->{'-outputref'} = \$text; 288 throw $E; 289}; 290return$text; 291 292}else{ 293my@lines= <$fh>; 294defined and chompfor@lines; 295try{ 296 _cmd_close($ctx,$fh); 297} catch Git::Error::Command with { 298my$E=shift; 299$E->{'-outputref'} = \@lines; 300 throw $E; 301}; 302return@lines; 303} 304} 305 306 307=item command_oneline ( COMMAND [, ARGUMENTS... ] ) 308 309=item command_oneline ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } ) 310 311Execute the given C<COMMAND> in the same way as command() 312does but always return a scalar string containing the first line 313of the command's standard output. 314 315=cut 316 317sub command_oneline { 318my($fh,$ctx) = command_output_pipe(@_); 319 320my$line= <$fh>; 321defined$lineand chomp$line; 322try{ 323 _cmd_close($ctx,$fh); 324} catch Git::Error::Command with { 325# Pepper with the output: 326my$E=shift; 327$E->{'-outputref'} = \$line; 328 throw $E; 329}; 330return$line; 331} 332 333 334=item command_output_pipe ( COMMAND [, ARGUMENTS... ] ) 335 336=item command_output_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } ) 337 338Execute the given C<COMMAND> in the same way as command() 339does but return a pipe filehandle from which the command output can be 340read. 341 342The function can return C<($pipe, $ctx)> in array context. 343See C<command_close_pipe()> for details. 344 345=cut 346 347sub command_output_pipe { 348 _command_common_pipe('-|',@_); 349} 350 351 352=item command_input_pipe ( COMMAND [, ARGUMENTS... ] ) 353 354=item command_input_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } ) 355 356Execute the given C<COMMAND> in the same way as command_output_pipe() 357does but return an input pipe filehandle instead; the command output 358is not captured. 359 360The function can return C<($pipe, $ctx)> in array context. 361See C<command_close_pipe()> for details. 362 363=cut 364 365sub command_input_pipe { 366 _command_common_pipe('|-',@_); 367} 368 369 370=item command_close_pipe ( PIPE [, CTX ] ) 371 372Close the C<PIPE> as returned from C<command_*_pipe()>, checking 373whether the command finished successfully. The optional C<CTX> argument 374is required if you want to see the command name in the error message, 375and it is the second value returned by C<command_*_pipe()> when 376called in array context. The call idiom is: 377 378 my ($fh, $ctx) = $r->command_output_pipe('status'); 379 while (<$fh>) { ... } 380 $r->command_close_pipe($fh, $ctx); 381 382Note that you should not rely on whatever actually is in C<CTX>; 383currently it is simply the command name but in future the context might 384have more complicated structure. 385 386=cut 387 388sub command_close_pipe { 389my($self,$fh,$ctx) = _maybe_self(@_); 390$ctx||='<unknown>'; 391 _cmd_close($ctx,$fh); 392} 393 394=item command_bidi_pipe ( COMMAND [, ARGUMENTS... ] ) 395 396Execute the given C<COMMAND> in the same way as command_output_pipe() 397does but return both an input pipe filehandle and an output pipe filehandle. 398 399The function will return C<($pid, $pipe_in, $pipe_out, $ctx)>. 400See C<command_close_bidi_pipe()> for details. 401 402=cut 403 404sub command_bidi_pipe { 405my($pid,$in,$out); 406my($self) = _maybe_self(@_); 407local%ENV=%ENV; 408my$cwd_save=undef; 409if($self) { 410shift; 411$cwd_save= cwd(); 412 _setup_git_cmd_env($self); 413} 414$pid= open2($in,$out,'git',@_); 415chdir($cwd_save)if$cwd_save; 416return($pid,$in,$out,join(' ',@_)); 417} 418 419=item command_close_bidi_pipe ( PID, PIPE_IN, PIPE_OUT [, CTX] ) 420 421Close the C<PIPE_IN> and C<PIPE_OUT> as returned from C<command_bidi_pipe()>, 422checking whether the command finished successfully. The optional C<CTX> 423argument is required if you want to see the command name in the error message, 424and it is the fourth value returned by C<command_bidi_pipe()>. The call idiom 425is: 426 427 my ($pid, $in, $out, $ctx) = $r->command_bidi_pipe('cat-file --batch-check'); 428 print $out "000000000\n"; 429 while (<$in>) { ... } 430 $r->command_close_bidi_pipe($pid, $in, $out, $ctx); 431 432Note that you should not rely on whatever actually is in C<CTX>; 433currently it is simply the command name but in future the context might 434have more complicated structure. 435 436C<PIPE_IN> and C<PIPE_OUT> may be C<undef> if they have been closed prior to 437calling this function. This may be useful in a query-response type of 438commands where caller first writes a query and later reads response, eg: 439 440 my ($pid, $in, $out, $ctx) = $r->command_bidi_pipe('cat-file --batch-check'); 441 print $out "000000000\n"; 442 close $out; 443 while (<$in>) { ... } 444 $r->command_close_bidi_pipe($pid, $in, undef, $ctx); 445 446This idiom may prevent potential dead locks caused by data sent to the output 447pipe not being flushed and thus not reaching the executed command. 448 449=cut 450 451sub command_close_bidi_pipe { 452local$?; 453my($self,$pid,$in,$out,$ctx) = _maybe_self(@_); 454 _cmd_close($ctx, (grep{defined} ($in,$out))); 455waitpid$pid,0; 456if($?>>8) { 457 throw Git::Error::Command($ctx,$?>>8); 458} 459} 460 461 462=item command_noisy ( COMMAND [, ARGUMENTS... ] ) 463 464Execute the given C<COMMAND> in the same way as command() does but do not 465capture the command output - the standard output is not redirected and goes 466to the standard output of the caller application. 467 468While the method is called command_noisy(), you might want to as well use 469it for the most silent Git commands which you know will never pollute your 470stdout but you want to avoid the overhead of the pipe setup when calling them. 471 472The function returns only after the command has finished running. 473 474=cut 475 476sub command_noisy { 477my($self,$cmd,@args) = _maybe_self(@_); 478 _check_valid_cmd($cmd); 479 480my$pid=fork; 481if(not defined$pid) { 482 throw Error::Simple("fork failed:$!"); 483}elsif($pid==0) { 484 _cmd_exec($self,$cmd,@args); 485} 486if(waitpid($pid,0) >0and$?>>8!=0) { 487 throw Git::Error::Command(join(' ',$cmd,@args),$?>>8); 488} 489} 490 491 492=item version () 493 494Return the Git version in use. 495 496=cut 497 498sub version { 499my$verstr= command_oneline('--version'); 500$verstr=~s/^git version //; 501$verstr; 502} 503 504 505=item exec_path () 506 507Return path to the Git sub-command executables (the same as 508C<git --exec-path>). Useful mostly only internally. 509 510=cut 511 512sub exec_path { command_oneline('--exec-path') } 513 514 515=item html_path () 516 517Return path to the Git html documentation (the same as 518C<git --html-path>). Useful mostly only internally. 519 520=cut 521 522sub html_path { command_oneline('--html-path') } 523 524 525=item get_tz_offset ( TIME ) 526 527Return the time zone offset from GMT in the form +/-HHMM where HH is 528the number of hours from GMT and MM is the number of minutes. This is 529the equivalent of what strftime("%z", ...) would provide on a GNU 530platform. 531 532If TIME is not supplied, the current local time is used. 533 534=cut 535 536sub get_tz_offset { 537# some systems don't handle or mishandle %z, so be creative. 538my$t=shift||time; 539my@t=localtime($t); 540$t[5] +=1900; 541my$gm= timegm(@t); 542my$sign=qw( + + - )[$gm<=>$t]; 543returnsprintf("%s%02d%02d",$sign, (gmtime(abs($t-$gm)))[2,1]); 544} 545 546=item get_record ( FILEHANDLE, INPUT_RECORD_SEPARATOR ) 547 548Read one record from FILEHANDLE delimited by INPUT_RECORD_SEPARATOR, 549removing any trailing INPUT_RECORD_SEPARATOR. 550 551=cut 552 553sub get_record { 554my($fh,$rs) =@_; 555local$/=$rs; 556my$rec= <$fh>; 557chomp$recifdefined$rs; 558$rec; 559} 560 561=item prompt ( PROMPT , ISPASSWORD ) 562 563Query user C<PROMPT> and return answer from user. 564 565Honours GIT_ASKPASS and SSH_ASKPASS environment variables for querying 566the user. If no *_ASKPASS variable is set or an error occoured, 567the terminal is tried as a fallback. 568If C<ISPASSWORD> is set and true, the terminal disables echo. 569 570=cut 571 572sub prompt { 573my($prompt,$isPassword) =@_; 574my$ret; 575if(exists$ENV{'GIT_ASKPASS'}) { 576$ret= _prompt($ENV{'GIT_ASKPASS'},$prompt); 577} 578if(!defined$ret&&exists$ENV{'SSH_ASKPASS'}) { 579$ret= _prompt($ENV{'SSH_ASKPASS'},$prompt); 580} 581if(!defined$ret) { 582print STDERR $prompt; 583 STDERR->flush; 584if(defined$isPassword&&$isPassword) { 585require Term::ReadKey; 586 Term::ReadKey::ReadMode('noecho'); 587$ret=''; 588while(defined(my$key= Term::ReadKey::ReadKey(0))) { 589last if$key=~/[\012\015]/;# \n\r 590$ret.=$key; 591} 592 Term::ReadKey::ReadMode('restore'); 593print STDERR "\n"; 594 STDERR->flush; 595}else{ 596chomp($ret= <STDIN>); 597} 598} 599return$ret; 600} 601 602sub _prompt { 603my($askpass,$prompt) =@_; 604return unlesslength$askpass; 605$prompt=~s/\n/ /g; 606my$ret; 607open my$fh,"-|",$askpass,$promptorreturn; 608$ret= <$fh>; 609$ret=~s/[\015\012]//g;# strip \r\n, chomp does not work on all systems (i.e. windows) as expected 610close($fh); 611return$ret; 612} 613 614=item repo_path () 615 616Return path to the git repository. Must be called on a repository instance. 617 618=cut 619 620sub repo_path {$_[0]->{opts}->{Repository} } 621 622 623=item wc_path () 624 625Return path to the working copy. Must be called on a repository instance. 626 627=cut 628 629sub wc_path {$_[0]->{opts}->{WorkingCopy} } 630 631 632=item wc_subdir () 633 634Return path to the subdirectory inside of a working copy. Must be called 635on a repository instance. 636 637=cut 638 639sub wc_subdir {$_[0]->{opts}->{WorkingSubdir} ||=''} 640 641 642=item wc_chdir ( SUBDIR ) 643 644Change the working copy subdirectory to work within. The C<SUBDIR> is 645relative to the working copy root directory (not the current subdirectory). 646Must be called on a repository instance attached to a working copy 647and the directory must exist. 648 649=cut 650 651sub wc_chdir { 652my($self,$subdir) =@_; 653$self->wc_path() 654or throw Error::Simple("bare repository"); 655 656-d $self->wc_path().'/'.$subdir 657or throw Error::Simple("subdir not found:$subdir$!"); 658# Of course we will not "hold" the subdirectory so anyone 659# can delete it now and we will never know. But at least we tried. 660 661$self->{opts}->{WorkingSubdir} =$subdir; 662} 663 664 665=item config ( VARIABLE ) 666 667Retrieve the configuration C<VARIABLE> in the same manner as C<config> 668does. In scalar context requires the variable to be set only one time 669(exception is thrown otherwise), in array context returns allows the 670variable to be set multiple times and returns all the values. 671 672=cut 673 674sub config { 675return _config_common({},@_); 676} 677 678 679=item config_bool ( VARIABLE ) 680 681Retrieve the bool configuration C<VARIABLE>. The return value 682is usable as a boolean in perl (and C<undef> if it's not defined, 683of course). 684 685=cut 686 687sub config_bool { 688my$val=scalar _config_common({'kind'=>'--bool'},@_); 689 690# Do not rewrite this as return (defined $val && $val eq 'true') 691# as some callers do care what kind of falsehood they receive. 692if(!defined$val) { 693returnundef; 694}else{ 695return$valeq'true'; 696} 697} 698 699 700=item config_path ( VARIABLE ) 701 702Retrieve the path configuration C<VARIABLE>. The return value 703is an expanded path or C<undef> if it's not defined. 704 705=cut 706 707sub config_path { 708return _config_common({'kind'=>'--path'},@_); 709} 710 711 712=item config_int ( VARIABLE ) 713 714Retrieve the integer configuration C<VARIABLE>. The return value 715is simple decimal number. An optional value suffix of 'k', 'm', 716or 'g' in the config file will cause the value to be multiplied 717by 1024, 1048576 (1024^2), or 1073741824 (1024^3) prior to output. 718It would return C<undef> if configuration variable is not defined. 719 720=cut 721 722sub config_int { 723returnscalar _config_common({'kind'=>'--int'},@_); 724} 725 726# Common subroutine to implement bulk of what the config* family of methods 727# do. This currently wraps command('config') so it is not so fast. 728sub _config_common { 729my($opts) =shift@_; 730my($self,$var) = _maybe_self(@_); 731 732try{ 733my@cmd= ('config',$opts->{'kind'} ?$opts->{'kind'} : ()); 734unshift@cmd,$selfif$self; 735if(wantarray) { 736return command(@cmd,'--get-all',$var); 737}else{ 738return command_oneline(@cmd,'--get',$var); 739} 740} catch Git::Error::Command with { 741my$E=shift; 742if($E->value() ==1) { 743# Key not found. 744return; 745}else{ 746 throw $E; 747} 748}; 749} 750 751=item get_colorbool ( NAME ) 752 753Finds if color should be used for NAMEd operation from the configuration, 754and returns boolean (true for "use color", false for "do not use color"). 755 756=cut 757 758sub get_colorbool { 759my($self,$var) =@_; 760my$stdout_to_tty= (-t STDOUT) ?"true":"false"; 761my$use_color=$self->command_oneline('config','--get-colorbool', 762$var,$stdout_to_tty); 763return($use_coloreq'true'); 764} 765 766=item get_color ( SLOT, COLOR ) 767 768Finds color for SLOT from the configuration, while defaulting to COLOR, 769and returns the ANSI color escape sequence: 770 771 print $repo->get_color("color.interactive.prompt", "underline blue white"); 772 print "some text"; 773 print $repo->get_color("", "normal"); 774 775=cut 776 777sub get_color { 778my($self,$slot,$default) =@_; 779my$color=$self->command_oneline('config','--get-color',$slot,$default); 780if(!defined$color) { 781$color=""; 782} 783return$color; 784} 785 786=item remote_refs ( REPOSITORY [, GROUPS [, REFGLOBS ] ] ) 787 788This function returns a hashref of refs stored in a given remote repository. 789The hash is in the format C<refname =\> hash>. For tags, the C<refname> entry 790contains the tag object while a C<refname^{}> entry gives the tagged objects. 791 792C<REPOSITORY> has the same meaning as the appropriate C<git-ls-remote> 793argument; either a URL or a remote name (if called on a repository instance). 794C<GROUPS> is an optional arrayref that can contain 'tags' to return all the 795tags and/or 'heads' to return all the heads. C<REFGLOB> is an optional array 796of strings containing a shell-like glob to further limit the refs returned in 797the hash; the meaning is again the same as the appropriate C<git-ls-remote> 798argument. 799 800This function may or may not be called on a repository instance. In the former 801case, remote names as defined in the repository are recognized as repository 802specifiers. 803 804=cut 805 806sub remote_refs { 807my($self,$repo,$groups,$refglobs) = _maybe_self(@_); 808my@args; 809if(ref$groupseq'ARRAY') { 810foreach(@$groups) { 811if($_eq'heads') { 812push(@args,'--heads'); 813}elsif($_eq'tags') { 814push(@args,'--tags'); 815}else{ 816# Ignore unknown groups for future 817# compatibility 818} 819} 820} 821push(@args,$repo); 822if(ref$refglobseq'ARRAY') { 823push(@args,@$refglobs); 824} 825 826my@self=$self? ($self) : ();# Ultra trickery 827my($fh,$ctx) = Git::command_output_pipe(@self,'ls-remote',@args); 828my%refs; 829while(<$fh>) { 830chomp; 831my($hash,$ref) =split(/\t/,$_,2); 832$refs{$ref} =$hash; 833} 834 Git::command_close_pipe(@self,$fh,$ctx); 835return \%refs; 836} 837 838 839=item ident ( TYPE | IDENTSTR ) 840 841=item ident_person ( TYPE | IDENTSTR | IDENTARRAY ) 842 843This suite of functions retrieves and parses ident information, as stored 844in the commit and tag objects or produced by C<var GIT_type_IDENT> (thus 845C<TYPE> can be either I<author> or I<committer>; case is insignificant). 846 847The C<ident> method retrieves the ident information from C<git var> 848and either returns it as a scalar string or as an array with the fields parsed. 849Alternatively, it can take a prepared ident string (e.g. from the commit 850object) and just parse it. 851 852C<ident_person> returns the person part of the ident - name and email; 853it can take the same arguments as C<ident> or the array returned by C<ident>. 854 855The synopsis is like: 856 857 my ($name, $email, $time_tz) = ident('author'); 858 "$name <$email>" eq ident_person('author'); 859 "$name <$email>" eq ident_person($name); 860 $time_tz =~ /^\d+ [+-]\d{4}$/; 861 862=cut 863 864sub ident { 865my($self,$type) = _maybe_self(@_); 866my$identstr; 867if(lc$typeeq lc'committer'or lc$typeeq lc'author') { 868my@cmd= ('var','GIT_'.uc($type).'_IDENT'); 869unshift@cmd,$selfif$self; 870$identstr= command_oneline(@cmd); 871}else{ 872$identstr=$type; 873} 874if(wantarray) { 875return$identstr=~/^(.*) <(.*)> (\d+ [+-]\d{4})$/; 876}else{ 877return$identstr; 878} 879} 880 881sub ident_person { 882my($self,@ident) = _maybe_self(@_); 883$#ident==0and@ident=$self?$self->ident($ident[0]) : ident($ident[0]); 884return"$ident[0] <$ident[1]>"; 885} 886 887=item hash_object ( TYPE, FILENAME ) 888 889Compute the SHA1 object id of the given C<FILENAME> considering it is 890of the C<TYPE> object type (C<blob>, C<commit>, C<tree>). 891 892The method can be called without any instance or on a specified Git repository, 893it makes zero difference. 894 895The function returns the SHA1 hash. 896 897=cut 898 899# TODO: Support for passing FILEHANDLE instead of FILENAME 900sub hash_object { 901my($self,$type,$file) = _maybe_self(@_); 902 command_oneline('hash-object','-t',$type,$file); 903} 904 905 906=item hash_and_insert_object ( FILENAME ) 907 908Compute the SHA1 object id of the given C<FILENAME> and add the object to the 909object database. 910 911The function returns the SHA1 hash. 912 913=cut 914 915# TODO: Support for passing FILEHANDLE instead of FILENAME 916sub hash_and_insert_object { 917my($self,$filename) =@_; 918 919 carp "Bad filename\"$filename\""if$filename=~/[\r\n]/; 920 921$self->_open_hash_and_insert_object_if_needed(); 922my($in,$out) = ($self->{hash_object_in},$self->{hash_object_out}); 923 924unless(print$out $filename,"\n") { 925$self->_close_hash_and_insert_object(); 926 throw Error::Simple("out pipe went bad"); 927} 928 929chomp(my$hash= <$in>); 930unless(defined($hash)) { 931$self->_close_hash_and_insert_object(); 932 throw Error::Simple("in pipe went bad"); 933} 934 935return$hash; 936} 937 938sub _open_hash_and_insert_object_if_needed { 939my($self) =@_; 940 941return ifdefined($self->{hash_object_pid}); 942 943($self->{hash_object_pid},$self->{hash_object_in}, 944$self->{hash_object_out},$self->{hash_object_ctx}) = 945$self->command_bidi_pipe(qw(hash-object -w --stdin-paths --no-filters)); 946} 947 948sub _close_hash_and_insert_object { 949my($self) =@_; 950 951return unlessdefined($self->{hash_object_pid}); 952 953my@vars=map{'hash_object_'.$_}qw(pid in out ctx); 954 955 command_close_bidi_pipe(@$self{@vars}); 956delete@$self{@vars}; 957} 958 959=item cat_blob ( SHA1, FILEHANDLE ) 960 961Prints the contents of the blob identified by C<SHA1> to C<FILEHANDLE> and 962returns the number of bytes printed. 963 964=cut 965 966sub cat_blob { 967my($self,$sha1,$fh) =@_; 968 969$self->_open_cat_blob_if_needed(); 970my($in,$out) = ($self->{cat_blob_in},$self->{cat_blob_out}); 971 972unless(print$out $sha1,"\n") { 973$self->_close_cat_blob(); 974 throw Error::Simple("out pipe went bad"); 975} 976 977my$description= <$in>; 978if($description=~/ missing$/) { 979 carp "$sha1doesn't exist in the repository"; 980return-1; 981} 982 983if($description!~/^[0-9a-fA-F]{40} \S+ (\d+)$/) { 984 carp "Unexpected result returned from git cat-file"; 985return-1; 986} 987 988my$size=$1; 989 990my$blob; 991my$bytesLeft=$size; 992 993while(1) { 994last unless$bytesLeft; 995 996my$bytesToRead=$bytesLeft<1024?$bytesLeft:1024; 997my$read=read($in,$blob,$bytesToRead); 998unless(defined($read)) { 999$self->_close_cat_blob();1000 throw Error::Simple("in pipe went bad");1001}1002unless(print$fh $blob) {1003$self->_close_cat_blob();1004 throw Error::Simple("couldn't write to passed in filehandle");1005}1006$bytesLeft-=$read;1007}10081009# Skip past the trailing newline.1010my$newline;1011my$read=read($in,$newline,1);1012unless(defined($read)) {1013$self->_close_cat_blob();1014 throw Error::Simple("in pipe went bad");1015}1016unless($read==1&&$newlineeq"\n") {1017$self->_close_cat_blob();1018 throw Error::Simple("didn't find newline after blob");1019}10201021return$size;1022}10231024sub _open_cat_blob_if_needed {1025my($self) =@_;10261027return ifdefined($self->{cat_blob_pid});10281029($self->{cat_blob_pid},$self->{cat_blob_in},1030$self->{cat_blob_out},$self->{cat_blob_ctx}) =1031$self->command_bidi_pipe(qw(cat-file --batch));1032}10331034sub _close_cat_blob {1035my($self) =@_;10361037return unlessdefined($self->{cat_blob_pid});10381039my@vars=map{'cat_blob_'.$_}qw(pid in out ctx);10401041 command_close_bidi_pipe(@$self{@vars});1042delete@$self{@vars};1043}104410451046=item credential_read( FILEHANDLE )10471048Reads credential key-value pairs from C<FILEHANDLE>. Reading stops at EOF or1049when an empty line is encountered. Each line must be of the form C<key=value>1050with a non-empty key. Function returns hash with all read values. Any white1051space (other than new-line character) is preserved.10521053=cut10541055sub credential_read {1056my($self,$reader) = _maybe_self(@_);1057my%credential;1058while(<$reader>) {1059chomp;1060if($_eq'') {1061last;1062}elsif(!/^([^=]+)=(.*)$/) {1063 throw Error::Simple("unable to parse git credential data:\n$_");1064}1065$credential{$1} =$2;1066}1067return%credential;1068}10691070=item credential_write( FILEHANDLE, CREDENTIAL_HASHREF )10711072Writes credential key-value pairs from hash referenced by1073C<CREDENTIAL_HASHREF> to C<FILEHANDLE>. Keys and values cannot contain1074new-lines or NUL bytes characters, and key cannot contain equal signs nor be1075empty (if they do Error::Simple is thrown). Any white space is preserved. If1076value for a key is C<undef>, it will be skipped.10771078If C<'url'> key exists it will be written first. (All the other key-value1079pairs are written in sorted order but you should not depend on that). Once1080all lines are written, an empty line is printed.10811082=cut10831084sub credential_write {1085my($self,$writer,$credential) = _maybe_self(@_);1086my($key,$value);10871088# Check if $credential is valid prior to writing anything1089while(($key,$value) =each%$credential) {1090if(!defined$key|| !length$key) {1091 throw Error::Simple("credential key empty or undefined");1092}elsif($key=~/[=\n\0]/) {1093 throw Error::Simple("credential key contains invalid characters:$key");1094}elsif(defined$value&&$value=~/[\n\0]/) {1095 throw Error::Simple("credential value for key=$keycontains invalid characters:$value");1096}1097}10981099for$key(sort{1100# url overwrites other fields, so it must come first1101return-1if$aeq'url';1102return1if$beq'url';1103return$acmp$b;1104}keys%$credential) {1105if(defined$credential->{$key}) {1106print$writer $key,'=',$credential->{$key},"\n";1107}1108}1109print$writer"\n";1110}11111112sub _credential_run {1113my($self,$credential,$op) = _maybe_self(@_);1114my($pid,$reader,$writer,$ctx) = command_bidi_pipe('credential',$op);11151116 credential_write $writer,$credential;1117close$writer;11181119if($opeq"fill") {1120%$credential= credential_read $reader;1121}1122if(<$reader>) {1123 throw Error::Simple("unexpected output from git credential$opresponse:\n$_\n");1124}11251126 command_close_bidi_pipe($pid,$reader,undef,$ctx);1127}11281129=item credential( CREDENTIAL_HASHREF [, OPERATION ] )11301131=item credential( CREDENTIAL_HASHREF, CODE )11321133Executes C<git credential> for a given set of credentials and specified1134operation. In both forms C<CREDENTIAL_HASHREF> needs to be a reference to1135a hash which stores credentials. Under certain conditions the hash can1136change.11371138In the first form, C<OPERATION> can be C<'fill'>, C<'approve'> or C<'reject'>,1139and function will execute corresponding C<git credential> sub-command. If1140it's omitted C<'fill'> is assumed. In case of C<'fill'> the values stored in1141C<CREDENTIAL_HASHREF> will be changed to the ones returned by the C<git1142credential fill> command. The usual usage would look something like:11431144 my %cred = (1145 'protocol' => 'https',1146 'host' => 'example.com',1147 'username' => 'bob'1148 );1149 Git::credential \%cred;1150 if (try_to_authenticate($cred{'username'}, $cred{'password'})) {1151 Git::credential \%cred, 'approve';1152 ... do more stuff ...1153 } else {1154 Git::credential \%cred, 'reject';1155 }11561157In the second form, C<CODE> needs to be a reference to a subroutine. The1158function will execute C<git credential fill> to fill the provided credential1159hash, then call C<CODE> with C<CREDENTIAL_HASHREF> as the sole argument. If1160C<CODE>'s return value is defined, the function will execute C<git credential1161approve> (if return value yields true) or C<git credential reject> (if return1162value is false). If the return value is undef, nothing at all is executed;1163this is useful, for example, if the credential could neither be verified nor1164rejected due to an unrelated network error. The return value is the same as1165what C<CODE> returns. With this form, the usage might look as follows:11661167 if (Git::credential {1168 'protocol' => 'https',1169 'host' => 'example.com',1170 'username' => 'bob'1171 }, sub {1172 my $cred = shift;1173 return !!try_to_authenticate($cred->{'username'},1174 $cred->{'password'});1175 }) {1176 ... do more stuff ...1177 }11781179=cut11801181sub credential {1182my($self,$credential,$op_or_code) = (_maybe_self(@_),'fill');11831184if('CODE'eq ref$op_or_code) {1185 _credential_run $credential,'fill';1186my$ret=$op_or_code->($credential);1187if(defined$ret) {1188 _credential_run $credential,$ret?'approve':'reject';1189}1190return$ret;1191}else{1192 _credential_run $credential,$op_or_code;1193}1194}11951196{# %TEMP_* Lexical Context11971198my(%TEMP_FILEMAP,%TEMP_FILES);11991200=item temp_acquire ( NAME )12011202Attempts to retrieve the temporary file mapped to the string C<NAME>. If an1203associated temp file has not been created this session or was closed, it is1204created, cached, and set for autoflush and binmode.12051206Internally locks the file mapped to C<NAME>. This lock must be released with1207C<temp_release()> when the temp file is no longer needed. Subsequent attempts1208to retrieve temporary files mapped to the same C<NAME> while still locked will1209cause an error. This locking mechanism provides a weak guarantee and is not1210threadsafe. It does provide some error checking to help prevent temp file refs1211writing over one another.12121213In general, the L<File::Handle> returned should not be closed by consumers as1214it defeats the purpose of this caching mechanism. If you need to close the temp1215file handle, then you should use L<File::Temp> or another temp file faculty1216directly. If a handle is closed and then requested again, then a warning will1217issue.12181219=cut12201221sub temp_acquire {1222my$temp_fd= _temp_cache(@_);12231224$TEMP_FILES{$temp_fd}{locked} =1;1225$temp_fd;1226}12271228=item temp_is_locked ( NAME )12291230Returns true if the internal lock created by a previous C<temp_acquire()>1231call with C<NAME> is still in effect.12321233When temp_acquire is called on a C<NAME>, it internally locks the temporary1234file mapped to C<NAME>. That lock will not be released until C<temp_release()>1235is called with either the original C<NAME> or the L<File::Handle> that was1236returned from the original call to temp_acquire.12371238Subsequent attempts to call C<temp_acquire()> with the same C<NAME> will fail1239unless there has been an intervening C<temp_release()> call for that C<NAME>1240(or its corresponding L<File::Handle> that was returned by the original1241C<temp_acquire()> call).12421243If true is returned by C<temp_is_locked()> for a C<NAME>, an attempt to1244C<temp_acquire()> the same C<NAME> will cause an error unless1245C<temp_release> is first called on that C<NAME> (or its corresponding1246L<File::Handle> that was returned by the original C<temp_acquire()> call).12471248=cut12491250sub temp_is_locked {1251my($self,$name) = _maybe_self(@_);1252my$temp_fd= \$TEMP_FILEMAP{$name};12531254defined$$temp_fd&&$$temp_fd->opened&&$TEMP_FILES{$$temp_fd}{locked};1255}12561257=item temp_release ( NAME )12581259=item temp_release ( FILEHANDLE )12601261Releases a lock acquired through C<temp_acquire()>. Can be called either with1262the C<NAME> mapping used when acquiring the temp file or with the C<FILEHANDLE>1263referencing a locked temp file.12641265Warns if an attempt is made to release a file that is not locked.12661267The temp file will be truncated before being released. This can help to reduce1268disk I/O where the system is smart enough to detect the truncation while data1269is in the output buffers. Beware that after the temp file is released and1270truncated, any operations on that file may fail miserably until it is1271re-acquired. All contents are lost between each release and acquire mapped to1272the same string.12731274=cut12751276sub temp_release {1277my($self,$temp_fd,$trunc) = _maybe_self(@_);12781279if(exists$TEMP_FILEMAP{$temp_fd}) {1280$temp_fd=$TEMP_FILES{$temp_fd};1281}1282unless($TEMP_FILES{$temp_fd}{locked}) {1283 carp "Attempt to release temp file '",1284$temp_fd,"' that has not been locked";1285}1286 temp_reset($temp_fd)if$truncand$temp_fd->opened;12871288$TEMP_FILES{$temp_fd}{locked} =0;1289undef;1290}12911292sub _temp_cache {1293my($self,$name) = _maybe_self(@_);12941295my$temp_fd= \$TEMP_FILEMAP{$name};1296if(defined$$temp_fdand$$temp_fd->opened) {1297if($TEMP_FILES{$$temp_fd}{locked}) {1298 throw Error::Simple("Temp file with moniker '".1299$name."' already in use");1300}1301}else{1302if(defined$$temp_fd) {1303# then we're here because of a closed handle.1304 carp "Temp file '",$name,1305"' was closed. Opening replacement.";1306}1307my$fname;13081309my$tmpdir;1310if(defined$self) {1311$tmpdir=$self->repo_path();1312}13131314my$n=$name;1315$n=~s/\W/_/g;# no strange chars13161317($$temp_fd,$fname) = File::Temp::tempfile(1318"Git_${n}_XXXXXX", UNLINK =>1, DIR =>$tmpdir,1319)or throw Error::Simple("couldn't open new temp file");13201321$$temp_fd->autoflush;1322binmode$$temp_fd;1323$TEMP_FILES{$$temp_fd}{fname} =$fname;1324}1325$$temp_fd;1326}13271328=item temp_reset ( FILEHANDLE )13291330Truncates and resets the position of the C<FILEHANDLE>.13311332=cut13331334sub temp_reset {1335my($self,$temp_fd) = _maybe_self(@_);13361337truncate$temp_fd,01338or throw Error::Simple("couldn't truncate file");1339sysseek($temp_fd,0, SEEK_SET)and seek($temp_fd,0, SEEK_SET)1340or throw Error::Simple("couldn't seek to beginning of file");1341sysseek($temp_fd,0, SEEK_CUR) ==0and tell($temp_fd) ==01342or throw Error::Simple("expected file position to be reset");1343}13441345=item temp_path ( NAME )13461347=item temp_path ( FILEHANDLE )13481349Returns the filename associated with the given tempfile.13501351=cut13521353sub temp_path {1354my($self,$temp_fd) = _maybe_self(@_);13551356if(exists$TEMP_FILEMAP{$temp_fd}) {1357$temp_fd=$TEMP_FILEMAP{$temp_fd};1358}1359$TEMP_FILES{$temp_fd}{fname};1360}13611362sub END{1363unlink values%TEMP_FILEMAPif%TEMP_FILEMAP;1364}13651366}# %TEMP_* Lexical Context13671368=item prefix_lines ( PREFIX, STRING [, STRING... ])13691370Prefixes lines in C<STRING> with C<PREFIX>.13711372=cut13731374sub prefix_lines {1375my$prefix=shift;1376my$string=join("\n",@_);1377$string=~s/^/$prefix/mg;1378return$string;1379}13801381=item unquote_path ( PATH )13821383Unquote a quoted path containing c-escapes as returned by ls-files etc.1384when not using -z or when parsing the output of diff -u.13851386=cut13871388{1389my%cquote_map= (1390"a"=>chr(7),1391"b"=>chr(8),1392"t"=>chr(9),1393"n"=>chr(10),1394"v"=>chr(11),1395"f"=>chr(12),1396"r"=>chr(13),1397"\\"=>"\\",1398"\042"=>"\042",1399);14001401sub unquote_path {1402local($_) =@_;1403my($retval,$remainder);1404if(!/^\042(.*)\042$/) {1405return$_;1406}1407($_,$retval) = ($1,"");1408while(/^([^\\]*)\\(.*)$/) {1409$remainder=$2;1410$retval.=$1;1411for($remainder) {1412if(/^([0-3][0-7][0-7])(.*)$/) {1413$retval.=chr(oct($1));1414$_=$2;1415last;1416}1417if(/^([\\\042abtnvfr])(.*)$/) {1418$retval.=$cquote_map{$1};1419$_=$2;1420last;1421}1422# This is malformed1423 throw Error::Simple("invalid quoted path$_[0]");1424}1425$_=$remainder;1426}1427$retval.=$_;1428return$retval;1429}1430}14311432=item get_comment_line_char ( )14331434Gets the core.commentchar configuration value.1435The value falls-back to '#' if core.commentchar is set to 'auto'.14361437=cut14381439sub get_comment_line_char {1440my$comment_line_char= config("core.commentchar") ||'#';1441$comment_line_char='#'if($comment_line_chareq'auto');1442$comment_line_char='#'if(length($comment_line_char) !=1);1443return$comment_line_char;1444}14451446=item comment_lines ( STRING [, STRING... ])14471448Comments lines following core.commentchar configuration.14491450=cut14511452sub comment_lines {1453my$comment_line_char= get_comment_line_char;1454return prefix_lines("$comment_line_char",@_);1455}14561457=back14581459=head1 ERROR HANDLING14601461All functions are supposed to throw Perl exceptions in case of errors.1462See the L<Error> module on how to catch those. Most exceptions are mere1463L<Error::Simple> instances.14641465However, the C<command()>, C<command_oneline()> and C<command_noisy()>1466functions suite can throw C<Git::Error::Command> exceptions as well: those are1467thrown when the external command returns an error code and contain the error1468code as well as access to the captured command's output. The exception class1469provides the usual C<stringify> and C<value> (command's exit code) methods and1470in addition also a C<cmd_output> method that returns either an array or a1471string with the captured command output (depending on the original function1472call context; C<command_noisy()> returns C<undef>) and $<cmdline> which1473returns the command and its arguments (but without proper quoting).14741475Note that the C<command_*_pipe()> functions cannot throw this exception since1476it has no idea whether the command failed or not. You will only find out1477at the time you C<close> the pipe; if you want to have that automated,1478use C<command_close_pipe()>, which can throw the exception.14791480=cut14811482{1483package Git::Error::Command;14841485@Git::Error::Command::ISA =qw(Error);14861487sub new {1488my$self=shift;1489my$cmdline=''.shift;1490my$value=0+shift;1491my$outputref=shift;1492my(@args) = ();14931494local$Error::Depth =$Error::Depth +1;14951496push(@args,'-cmdline',$cmdline);1497push(@args,'-value',$value);1498push(@args,'-outputref',$outputref);14991500$self->SUPER::new(-text =>'command returned error',@args);1501}15021503sub stringify {1504my$self=shift;1505my$text=$self->SUPER::stringify;1506$self->cmdline() .': '.$text.': '.$self->value() ."\n";1507}15081509sub cmdline {1510my$self=shift;1511$self->{'-cmdline'};1512}15131514sub cmd_output {1515my$self=shift;1516my$ref=$self->{'-outputref'};1517defined$refor undef;1518if(ref$refeq'ARRAY') {1519return@$ref;1520}else{# SCALAR1521return$$ref;1522}1523}1524}15251526=over 415271528=item git_cmd_try { CODE } ERRMSG15291530This magical statement will automatically catch any C<Git::Error::Command>1531exceptions thrown by C<CODE> and make your program die with C<ERRMSG>1532on its lips; the message will have %s substituted for the command line1533and %d for the exit status. This statement is useful mostly for producing1534more user-friendly error messages.15351536In case of no exception caught the statement returns C<CODE>'s return value.15371538Note that this is the only auto-exported function.15391540=cut15411542sub git_cmd_try(&$) {1543my($code,$errmsg) =@_;1544my@result;1545my$err;1546my$array=wantarray;1547try{1548if($array) {1549@result= &$code;1550}else{1551$result[0] = &$code;1552}1553} catch Git::Error::Command with {1554my$E=shift;1555$err=$errmsg;1556$err=~s/\%s/$E->cmdline()/ge;1557$err=~s/\%d/$E->value()/ge;1558# We can't croak here since Error.pm would mangle1559# that to Error::Simple.1560};1561$errand croak $err;1562return$array?@result:$result[0];1563}156415651566=back15671568=head1 COPYRIGHT15691570Copyright 2006 by Petr Baudis E<lt>pasky@suse.czE<gt>.15711572This module is free software; it may be used, copied, modified1573and distributed under the terms of the GNU General Public Licence,1574either version 2, or (at your option) any later version.15751576=cut157715781579# Take raw method argument list and return ($obj, @args) in case1580# the method was called upon an instance and (undef, @args) if1581# it was called directly.1582sub _maybe_self {1583 UNIVERSAL::isa($_[0],'Git') ?@_: (undef,@_);1584}15851586# Check if the command id is something reasonable.1587sub _check_valid_cmd {1588my($cmd) =@_;1589$cmd=~/^[a-z0-9A-Z_-]+$/or throw Error::Simple("bad command:$cmd");1590}15911592# Common backend for the pipe creators.1593sub _command_common_pipe {1594my$direction=shift;1595my($self,@p) = _maybe_self(@_);1596my(%opts,$cmd,@args);1597if(ref$p[0]) {1598($cmd,@args) = @{shift@p};1599%opts=ref$p[0] ? %{$p[0]} :@p;1600}else{1601($cmd,@args) =@p;1602}1603 _check_valid_cmd($cmd);16041605my$fh;1606if($^Oeq'MSWin32') {1607# ActiveState Perl1608#defined $opts{STDERR} and1609# warn 'ignoring STDERR option - running w/ ActiveState';1610$directioneq'-|'or1611die'input pipe for ActiveState not implemented';1612# the strange construction with *ACPIPE is just to1613# explain the tie below that we want to bind to1614# a handle class, not scalar. It is not known if1615# it is something specific to ActiveState Perl or1616# just a Perl quirk.1617 tie (*ACPIPE,'Git::activestate_pipe',$cmd,@args);1618$fh= *ACPIPE;16191620}else{1621my$pid=open($fh,$direction);1622if(not defined$pid) {1623 throw Error::Simple("open failed:$!");1624}elsif($pid==0) {1625if($opts{STDERR}) {1626open(STDERR,'>&',$opts{STDERR})1627or die"dup failed:$!";1628}elsif(defined$opts{STDERR}) {1629open(STDERR,'>','/dev/null')1630or die"opening /dev/null failed:$!";1631}1632 _cmd_exec($self,$cmd,@args);1633}1634}1635returnwantarray? ($fh,join(' ',$cmd,@args)) :$fh;1636}16371638# When already in the subprocess, set up the appropriate state1639# for the given repository and execute the git command.1640sub _cmd_exec {1641my($self,@args) =@_;1642 _setup_git_cmd_env($self);1643 _execv_git_cmd(@args);1644dieqq[exec "@args" failed:$!];1645}16461647# set up the appropriate state for git command1648sub _setup_git_cmd_env {1649my$self=shift;1650if($self) {1651$self->repo_path()and$ENV{'GIT_DIR'} =$self->repo_path();1652$self->repo_path()and$self->wc_path()1653and$ENV{'GIT_WORK_TREE'} =$self->wc_path();1654$self->wc_path()and chdir($self->wc_path());1655$self->wc_subdir()and chdir($self->wc_subdir());1656}1657}16581659# Execute the given Git command ($_[0]) with arguments ($_[1..])1660# by searching for it at proper places.1661sub _execv_git_cmd {exec('git',@_); }16621663# Close pipe to a subprocess.1664sub _cmd_close {1665my$ctx=shift@_;1666foreachmy$fh(@_) {1667if(close$fh) {1668# nop1669}elsif($!) {1670# It's just close, no point in fatalities1671 carp "error closing pipe:$!";1672}elsif($?>>8) {1673# The caller should pepper this.1674 throw Git::Error::Command($ctx,$?>>8);1675}1676# else we might e.g. closed a live stream; the command1677# dying of SIGPIPE would drive us here.1678}1679}168016811682sub DESTROY {1683my($self) =@_;1684$self->_close_hash_and_insert_object();1685$self->_close_cat_blob();1686}168716881689# Pipe implementation for ActiveState Perl.16901691package Git::activestate_pipe;16921693sub TIEHANDLE {1694my($class,@params) =@_;1695# FIXME: This is probably horrible idea and the thing will explode1696# at the moment you give it arguments that require some quoting,1697# but I have no ActiveState clue... --pasky1698# Let's just hope ActiveState Perl does at least the quoting1699# correctly.1700my@data=qx{git@params};1701bless{ i =>0, data => \@data},$class;1702}17031704sub READLINE {1705my$self=shift;1706if($self->{i} >=scalar@{$self->{data}}) {1707returnundef;1708}1709my$i=$self->{i};1710if(wantarray) {1711$self->{i} =$#{$self->{'data'}} +1;1712returnsplice(@{$self->{'data'}},$i);1713}1714$self->{i} =$i+1;1715return$self->{'data'}->[$i];1716}17171718sub CLOSE {1719my$self=shift;1720delete$self->{data};1721delete$self->{i};1722}17231724sub EOF {1725my$self=shift;1726return($self->{i} >=scalar@{$self->{data}});1727}1728172917301;# Famous last words