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; 12 13 14BEGIN{ 15 16our($VERSION,@ISA,@EXPORT,@EXPORT_OK); 17 18# Totally unstable API. 19$VERSION='0.01'; 20 21 22=head1 SYNOPSIS 23 24 use Git; 25 26 my $version = Git::command_oneline('version'); 27 28 git_cmd_try { Git::command_noisy('update-server-info') } 29 '%s failed w/ code %d'; 30 31 my $repo = Git->repository (Directory => '/srv/git/cogito.git'); 32 33 34 my @revs = $repo->command('rev-list', '--since=last monday', '--all'); 35 36 my ($fh, $c) = $repo->command_output_pipe('rev-list', '--since=last monday', '--all'); 37 my $lastrev = <$fh>; chomp $lastrev; 38 $repo->command_close_pipe($fh, $c); 39 40 my $lastrev = $repo->command_oneline( [ 'rev-list', '--all' ], 41 STDERR => 0 ); 42 43 my $sha1 = $repo->hash_and_insert_object('file.txt'); 44 my $tempfile = tempfile(); 45 my $size = $repo->cat_blob($sha1, $tempfile); 46 47=cut 48 49 50require Exporter; 51 52@ISA=qw(Exporter); 53 54@EXPORT=qw(git_cmd_try); 55 56# Methods which can be called as standalone functions as well: 57@EXPORT_OK=qw(command command_oneline command_noisy 58 command_output_pipe command_input_pipe command_close_pipe 59 command_bidi_pipe command_close_bidi_pipe 60 version exec_path html_path hash_object git_cmd_try 61 remote_refs 62 temp_acquire temp_release temp_reset temp_path); 63 64 65=head1 DESCRIPTION 66 67This module provides Perl scripts easy way to interface the Git version control 68system. The modules have an easy and well-tested way to call arbitrary Git 69commands; in the future, the interface will also provide specialized methods 70for doing easily operations which are not totally trivial to do over 71the generic command interface. 72 73While some commands can be executed outside of any context (e.g. 'version' 74or 'init'), most operations require a repository context, which in practice 75means getting an instance of the Git object using the repository() constructor. 76(In the future, we will also get a new_repository() constructor.) All commands 77called as methods of the object are then executed in the context of the 78repository. 79 80Part of the "repository state" is also information about path to the attached 81working copy (unless you work with a bare repository). You can also navigate 82inside of the working copy using the C<wc_chdir()> method. (Note that 83the repository object is self-contained and will not change working directory 84of your process.) 85 86TODO: In the future, we might also do 87 88 my $remoterepo = $repo->remote_repository (Name => 'cogito', Branch => 'master'); 89 $remoterepo ||= Git->remote_repository ('http://git.or.cz/cogito.git/'); 90 my @refs = $remoterepo->refs(); 91 92Currently, the module merely wraps calls to external Git tools. In the future, 93it will provide a much faster way to interact with Git by linking directly 94to libgit. This should be completely opaque to the user, though (performance 95increase notwithstanding). 96 97=cut 98 99 100use Carp qw(carp croak);# but croak is bad - throw instead 101use Error qw(:try); 102use Cwd qw(abs_path); 103use IPC::Open2 qw(open2); 104use Fcntl qw(SEEK_SET SEEK_CUR); 105} 106 107 108=head1 CONSTRUCTORS 109 110=over 4 111 112=item repository ( OPTIONS ) 113 114=item repository ( DIRECTORY ) 115 116=item repository () 117 118Construct a new repository object. 119C<OPTIONS> are passed in a hash like fashion, using key and value pairs. 120Possible options are: 121 122B<Repository> - Path to the Git repository. 123 124B<WorkingCopy> - Path to the associated working copy; not strictly required 125as many commands will happily crunch on a bare repository. 126 127B<WorkingSubdir> - Subdirectory in the working copy to work inside. 128Just left undefined if you do not want to limit the scope of operations. 129 130B<Directory> - Path to the Git working directory in its usual setup. 131The C<.git> directory is searched in the directory and all the parent 132directories; if found, C<WorkingCopy> is set to the directory containing 133it and C<Repository> to the C<.git> directory itself. If no C<.git> 134directory was found, the C<Directory> is assumed to be a bare repository, 135C<Repository> is set to point at it and C<WorkingCopy> is left undefined. 136If the C<$GIT_DIR> environment variable is set, things behave as expected 137as well. 138 139You should not use both C<Directory> and either of C<Repository> and 140C<WorkingCopy> - the results of that are undefined. 141 142Alternatively, a directory path may be passed as a single scalar argument 143to the constructor; it is equivalent to setting only the C<Directory> option 144field. 145 146Calling the constructor with no options whatsoever is equivalent to 147calling it with C<< Directory => '.' >>. In general, if you are building 148a standard porcelain command, simply doing C<< Git->repository() >> should 149do the right thing and setup the object to reflect exactly where the user 150is right now. 151 152=cut 153 154sub repository { 155my$class=shift; 156my@args=@_; 157my%opts= (); 158my$self; 159 160if(defined$args[0]) { 161if($#args%2!=1) { 162# Not a hash. 163$#args==0or throw Error::Simple("bad usage"); 164%opts= ( Directory =>$args[0] ); 165}else{ 166%opts=@args; 167} 168} 169 170if(not defined$opts{Repository}and not defined$opts{WorkingCopy} 171and not defined$opts{Directory}) { 172$opts{Directory} ='.'; 173} 174 175if(defined$opts{Directory}) { 176-d $opts{Directory}or throw Error::Simple("Directory not found:$opts{Directory}$!"); 177 178my$search= Git->repository(WorkingCopy =>$opts{Directory}); 179my$dir; 180try{ 181$dir=$search->command_oneline(['rev-parse','--git-dir'], 182 STDERR =>0); 183} catch Git::Error::Command with { 184$dir=undef; 185}; 186 187if($dir) { 188$dir=~ m#^/# or $dir = $opts{Directory} . '/' . $dir; 189$opts{Repository} = abs_path($dir); 190 191# If --git-dir went ok, this shouldn't die either. 192my$prefix=$search->command_oneline('rev-parse','--show-prefix'); 193$dir= abs_path($opts{Directory}) .'/'; 194if($prefix) { 195if(substr($dir, -length($prefix))ne$prefix) { 196 throw Error::Simple("rev-parse confused me -$dirdoes not have trailing$prefix"); 197} 198substr($dir, -length($prefix)) =''; 199} 200$opts{WorkingCopy} =$dir; 201$opts{WorkingSubdir} =$prefix; 202 203}else{ 204# A bare repository? Let's see... 205$dir=$opts{Directory}; 206 207unless(-d "$dir/refs"and-d "$dir/objects"and-e "$dir/HEAD") { 208# Mimic git-rev-parse --git-dir error message: 209 throw Error::Simple("fatal: Not a git repository:$dir"); 210} 211my$search= Git->repository(Repository =>$dir); 212try{ 213$search->command('symbolic-ref','HEAD'); 214} catch Git::Error::Command with { 215# Mimic git-rev-parse --git-dir error message: 216 throw Error::Simple("fatal: Not a git repository:$dir"); 217} 218 219$opts{Repository} = abs_path($dir); 220} 221 222delete$opts{Directory}; 223} 224 225$self= { opts => \%opts}; 226bless$self,$class; 227} 228 229=back 230 231=head1 METHODS 232 233=over 4 234 235=item command ( COMMAND [, ARGUMENTS... ] ) 236 237=item command ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } ) 238 239Execute the given Git C<COMMAND> (specify it without the 'git-' 240prefix), optionally with the specified extra C<ARGUMENTS>. 241 242The second more elaborate form can be used if you want to further adjust 243the command execution. Currently, only one option is supported: 244 245B<STDERR> - How to deal with the command's error output. By default (C<undef>) 246it is delivered to the caller's C<STDERR>. A false value (0 or '') will cause 247it to be thrown away. If you want to process it, you can get it in a filehandle 248you specify, but you must be extremely careful; if the error output is not 249very short and you want to read it in the same process as where you called 250C<command()>, you are set up for a nice deadlock! 251 252The method can be called without any instance or on a specified Git repository 253(in that case the command will be run in the repository context). 254 255In scalar context, it returns all the command output in a single string 256(verbatim). 257 258In array context, it returns an array containing lines printed to the 259command's stdout (without trailing newlines). 260 261In both cases, the command's stdin and stderr are the same as the caller's. 262 263=cut 264 265sub command { 266my($fh,$ctx) = command_output_pipe(@_); 267 268if(not defined wantarray) { 269# Nothing to pepper the possible exception with. 270 _cmd_close($fh,$ctx); 271 272}elsif(not wantarray) { 273local$/; 274my$text= <$fh>; 275try{ 276 _cmd_close($fh,$ctx); 277} catch Git::Error::Command with { 278# Pepper with the output: 279my$E=shift; 280$E->{'-outputref'} = \$text; 281 throw $E; 282}; 283return$text; 284 285}else{ 286my@lines= <$fh>; 287defined and chompfor@lines; 288try{ 289 _cmd_close($fh,$ctx); 290} catch Git::Error::Command with { 291my$E=shift; 292$E->{'-outputref'} = \@lines; 293 throw $E; 294}; 295return@lines; 296} 297} 298 299 300=item command_oneline ( COMMAND [, ARGUMENTS... ] ) 301 302=item command_oneline ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } ) 303 304Execute the given C<COMMAND> in the same way as command() 305does but always return a scalar string containing the first line 306of the command's standard output. 307 308=cut 309 310sub command_oneline { 311my($fh,$ctx) = command_output_pipe(@_); 312 313my$line= <$fh>; 314defined$lineand chomp$line; 315try{ 316 _cmd_close($fh,$ctx); 317} catch Git::Error::Command with { 318# Pepper with the output: 319my$E=shift; 320$E->{'-outputref'} = \$line; 321 throw $E; 322}; 323return$line; 324} 325 326 327=item command_output_pipe ( COMMAND [, ARGUMENTS... ] ) 328 329=item command_output_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } ) 330 331Execute the given C<COMMAND> in the same way as command() 332does but return a pipe filehandle from which the command output can be 333read. 334 335The function can return C<($pipe, $ctx)> in array context. 336See C<command_close_pipe()> for details. 337 338=cut 339 340sub command_output_pipe { 341 _command_common_pipe('-|',@_); 342} 343 344 345=item command_input_pipe ( COMMAND [, ARGUMENTS... ] ) 346 347=item command_input_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } ) 348 349Execute the given C<COMMAND> in the same way as command_output_pipe() 350does but return an input pipe filehandle instead; the command output 351is not captured. 352 353The function can return C<($pipe, $ctx)> in array context. 354See C<command_close_pipe()> for details. 355 356=cut 357 358sub command_input_pipe { 359 _command_common_pipe('|-',@_); 360} 361 362 363=item command_close_pipe ( PIPE [, CTX ] ) 364 365Close the C<PIPE> as returned from C<command_*_pipe()>, checking 366whether the command finished successfully. The optional C<CTX> argument 367is required if you want to see the command name in the error message, 368and it is the second value returned by C<command_*_pipe()> when 369called in array context. The call idiom is: 370 371 my ($fh, $ctx) = $r->command_output_pipe('status'); 372 while (<$fh>) { ... } 373 $r->command_close_pipe($fh, $ctx); 374 375Note that you should not rely on whatever actually is in C<CTX>; 376currently it is simply the command name but in future the context might 377have more complicated structure. 378 379=cut 380 381sub command_close_pipe { 382my($self,$fh,$ctx) = _maybe_self(@_); 383$ctx||='<unknown>'; 384 _cmd_close($fh,$ctx); 385} 386 387=item command_bidi_pipe ( COMMAND [, ARGUMENTS... ] ) 388 389Execute the given C<COMMAND> in the same way as command_output_pipe() 390does but return both an input pipe filehandle and an output pipe filehandle. 391 392The function will return return C<($pid, $pipe_in, $pipe_out, $ctx)>. 393See C<command_close_bidi_pipe()> for details. 394 395=cut 396 397sub command_bidi_pipe { 398my($pid,$in,$out); 399$pid= open2($in,$out,'git',@_); 400return($pid,$in,$out,join(' ',@_)); 401} 402 403=item command_close_bidi_pipe ( PID, PIPE_IN, PIPE_OUT [, CTX] ) 404 405Close the C<PIPE_IN> and C<PIPE_OUT> as returned from C<command_bidi_pipe()>, 406checking whether the command finished successfully. The optional C<CTX> 407argument is required if you want to see the command name in the error message, 408and it is the fourth value returned by C<command_bidi_pipe()>. The call idiom 409is: 410 411 my ($pid, $in, $out, $ctx) = $r->command_bidi_pipe('cat-file --batch-check'); 412 print "000000000\n" $out; 413 while (<$in>) { ... } 414 $r->command_close_bidi_pipe($pid, $in, $out, $ctx); 415 416Note that you should not rely on whatever actually is in C<CTX>; 417currently it is simply the command name but in future the context might 418have more complicated structure. 419 420=cut 421 422sub command_close_bidi_pipe { 423local$?; 424my($pid,$in,$out,$ctx) =@_; 425foreachmy$fh($in,$out) { 426unless(close$fh) { 427if($!) { 428 carp "error closing pipe:$!"; 429}elsif($?>>8) { 430 throw Git::Error::Command($ctx,$?>>8); 431} 432} 433} 434 435waitpid$pid,0; 436 437if($?>>8) { 438 throw Git::Error::Command($ctx,$?>>8); 439} 440} 441 442 443=item command_noisy ( COMMAND [, ARGUMENTS... ] ) 444 445Execute the given C<COMMAND> in the same way as command() does but do not 446capture the command output - the standard output is not redirected and goes 447to the standard output of the caller application. 448 449While the method is called command_noisy(), you might want to as well use 450it for the most silent Git commands which you know will never pollute your 451stdout but you want to avoid the overhead of the pipe setup when calling them. 452 453The function returns only after the command has finished running. 454 455=cut 456 457sub command_noisy { 458my($self,$cmd,@args) = _maybe_self(@_); 459 _check_valid_cmd($cmd); 460 461my$pid=fork; 462if(not defined$pid) { 463 throw Error::Simple("fork failed:$!"); 464}elsif($pid==0) { 465 _cmd_exec($self,$cmd,@args); 466} 467if(waitpid($pid,0) >0and$?>>8!=0) { 468 throw Git::Error::Command(join(' ',$cmd,@args),$?>>8); 469} 470} 471 472 473=item version () 474 475Return the Git version in use. 476 477=cut 478 479sub version { 480my$verstr= command_oneline('--version'); 481$verstr=~s/^git version //; 482$verstr; 483} 484 485 486=item exec_path () 487 488Return path to the Git sub-command executables (the same as 489C<git --exec-path>). Useful mostly only internally. 490 491=cut 492 493sub exec_path { command_oneline('--exec-path') } 494 495 496=item html_path () 497 498Return path to the Git html documentation (the same as 499C<git --html-path>). Useful mostly only internally. 500 501=cut 502 503sub html_path { command_oneline('--html-path') } 504 505 506=item repo_path () 507 508Return path to the git repository. Must be called on a repository instance. 509 510=cut 511 512sub repo_path {$_[0]->{opts}->{Repository} } 513 514 515=item wc_path () 516 517Return path to the working copy. Must be called on a repository instance. 518 519=cut 520 521sub wc_path {$_[0]->{opts}->{WorkingCopy} } 522 523 524=item wc_subdir () 525 526Return path to the subdirectory inside of a working copy. Must be called 527on a repository instance. 528 529=cut 530 531sub wc_subdir {$_[0]->{opts}->{WorkingSubdir} ||=''} 532 533 534=item wc_chdir ( SUBDIR ) 535 536Change the working copy subdirectory to work within. The C<SUBDIR> is 537relative to the working copy root directory (not the current subdirectory). 538Must be called on a repository instance attached to a working copy 539and the directory must exist. 540 541=cut 542 543sub wc_chdir { 544my($self,$subdir) =@_; 545$self->wc_path() 546or throw Error::Simple("bare repository"); 547 548-d $self->wc_path().'/'.$subdir 549or throw Error::Simple("subdir not found:$subdir$!"); 550# Of course we will not "hold" the subdirectory so anyone 551# can delete it now and we will never know. But at least we tried. 552 553$self->{opts}->{WorkingSubdir} =$subdir; 554} 555 556 557=item config ( VARIABLE ) 558 559Retrieve the configuration C<VARIABLE> in the same manner as C<config> 560does. In scalar context requires the variable to be set only one time 561(exception is thrown otherwise), in array context returns allows the 562variable to be set multiple times and returns all the values. 563 564This currently wraps command('config') so it is not so fast. 565 566=cut 567 568sub config { 569my($self,$var) = _maybe_self(@_); 570 571try{ 572my@cmd= ('config'); 573unshift@cmd,$selfif$self; 574if(wantarray) { 575return command(@cmd,'--get-all',$var); 576}else{ 577return command_oneline(@cmd,'--get',$var); 578} 579} catch Git::Error::Command with { 580my$E=shift; 581if($E->value() ==1) { 582# Key not found. 583return; 584}else{ 585 throw $E; 586} 587}; 588} 589 590 591=item config_bool ( VARIABLE ) 592 593Retrieve the bool configuration C<VARIABLE>. The return value 594is usable as a boolean in perl (and C<undef> if it's not defined, 595of course). 596 597This currently wraps command('config') so it is not so fast. 598 599=cut 600 601sub config_bool { 602my($self,$var) = _maybe_self(@_); 603 604try{ 605my@cmd= ('config','--bool','--get',$var); 606unshift@cmd,$selfif$self; 607my$val= command_oneline(@cmd); 608returnundefunlessdefined$val; 609return$valeq'true'; 610} catch Git::Error::Command with { 611my$E=shift; 612if($E->value() ==1) { 613# Key not found. 614returnundef; 615}else{ 616 throw $E; 617} 618}; 619} 620 621=item config_int ( VARIABLE ) 622 623Retrieve the integer configuration C<VARIABLE>. The return value 624is simple decimal number. An optional value suffix of 'k', 'm', 625or 'g' in the config file will cause the value to be multiplied 626by 1024, 1048576 (1024^2), or 1073741824 (1024^3) prior to output. 627It would return C<undef> if configuration variable is not defined, 628 629This currently wraps command('config') so it is not so fast. 630 631=cut 632 633sub config_int { 634my($self,$var) = _maybe_self(@_); 635 636try{ 637my@cmd= ('config','--int','--get',$var); 638unshift@cmd,$selfif$self; 639return command_oneline(@cmd); 640} catch Git::Error::Command with { 641my$E=shift; 642if($E->value() ==1) { 643# Key not found. 644returnundef; 645}else{ 646 throw $E; 647} 648}; 649} 650 651=item get_colorbool ( NAME ) 652 653Finds if color should be used for NAMEd operation from the configuration, 654and returns boolean (true for "use color", false for "do not use color"). 655 656=cut 657 658sub get_colorbool { 659my($self,$var) =@_; 660my$stdout_to_tty= (-t STDOUT) ?"true":"false"; 661my$use_color=$self->command_oneline('config','--get-colorbool', 662$var,$stdout_to_tty); 663return($use_coloreq'true'); 664} 665 666=item get_color ( SLOT, COLOR ) 667 668Finds color for SLOT from the configuration, while defaulting to COLOR, 669and returns the ANSI color escape sequence: 670 671 print $repo->get_color("color.interactive.prompt", "underline blue white"); 672 print "some text"; 673 print $repo->get_color("", "normal"); 674 675=cut 676 677sub get_color { 678my($self,$slot,$default) =@_; 679my$color=$self->command_oneline('config','--get-color',$slot,$default); 680if(!defined$color) { 681$color=""; 682} 683return$color; 684} 685 686=item remote_refs ( REPOSITORY [, GROUPS [, REFGLOBS ] ] ) 687 688This function returns a hashref of refs stored in a given remote repository. 689The hash is in the format C<refname =\> hash>. For tags, the C<refname> entry 690contains the tag object while a C<refname^{}> entry gives the tagged objects. 691 692C<REPOSITORY> has the same meaning as the appropriate C<git-ls-remote> 693argument; either an URL or a remote name (if called on a repository instance). 694C<GROUPS> is an optional arrayref that can contain 'tags' to return all the 695tags and/or 'heads' to return all the heads. C<REFGLOB> is an optional array 696of strings containing a shell-like glob to further limit the refs returned in 697the hash; the meaning is again the same as the appropriate C<git-ls-remote> 698argument. 699 700This function may or may not be called on a repository instance. In the former 701case, remote names as defined in the repository are recognized as repository 702specifiers. 703 704=cut 705 706sub remote_refs { 707my($self,$repo,$groups,$refglobs) = _maybe_self(@_); 708my@args; 709if(ref$groupseq'ARRAY') { 710foreach(@$groups) { 711if($_eq'heads') { 712push(@args,'--heads'); 713}elsif($_eq'tags') { 714push(@args,'--tags'); 715}else{ 716# Ignore unknown groups for future 717# compatibility 718} 719} 720} 721push(@args,$repo); 722if(ref$refglobseq'ARRAY') { 723push(@args,@$refglobs); 724} 725 726my@self=$self? ($self) : ();# Ultra trickery 727my($fh,$ctx) = Git::command_output_pipe(@self,'ls-remote',@args); 728my%refs; 729while(<$fh>) { 730chomp; 731my($hash,$ref) =split(/\t/,$_,2); 732$refs{$ref} =$hash; 733} 734 Git::command_close_pipe(@self,$fh,$ctx); 735return \%refs; 736} 737 738 739=item ident ( TYPE | IDENTSTR ) 740 741=item ident_person ( TYPE | IDENTSTR | IDENTARRAY ) 742 743This suite of functions retrieves and parses ident information, as stored 744in the commit and tag objects or produced by C<var GIT_type_IDENT> (thus 745C<TYPE> can be either I<author> or I<committer>; case is insignificant). 746 747The C<ident> method retrieves the ident information from C<git var> 748and either returns it as a scalar string or as an array with the fields parsed. 749Alternatively, it can take a prepared ident string (e.g. from the commit 750object) and just parse it. 751 752C<ident_person> returns the person part of the ident - name and email; 753it can take the same arguments as C<ident> or the array returned by C<ident>. 754 755The synopsis is like: 756 757 my ($name, $email, $time_tz) = ident('author'); 758 "$name <$email>" eq ident_person('author'); 759 "$name <$email>" eq ident_person($name); 760 $time_tz =~ /^\d+ [+-]\d{4}$/; 761 762=cut 763 764sub ident { 765my($self,$type) = _maybe_self(@_); 766my$identstr; 767if(lc$typeeq lc'committer'or lc$typeeq lc'author') { 768my@cmd= ('var','GIT_'.uc($type).'_IDENT'); 769unshift@cmd,$selfif$self; 770$identstr= command_oneline(@cmd); 771}else{ 772$identstr=$type; 773} 774if(wantarray) { 775return$identstr=~/^(.*) <(.*)> (\d+ [+-]\d{4})$/; 776}else{ 777return$identstr; 778} 779} 780 781sub ident_person { 782my($self,@ident) = _maybe_self(@_); 783$#ident==0and@ident=$self?$self->ident($ident[0]) : ident($ident[0]); 784return"$ident[0] <$ident[1]>"; 785} 786 787 788=item hash_object ( TYPE, FILENAME ) 789 790Compute the SHA1 object id of the given C<FILENAME> considering it is 791of the C<TYPE> object type (C<blob>, C<commit>, C<tree>). 792 793The method can be called without any instance or on a specified Git repository, 794it makes zero difference. 795 796The function returns the SHA1 hash. 797 798=cut 799 800# TODO: Support for passing FILEHANDLE instead of FILENAME 801sub hash_object { 802my($self,$type,$file) = _maybe_self(@_); 803 command_oneline('hash-object','-t',$type,$file); 804} 805 806 807=item hash_and_insert_object ( FILENAME ) 808 809Compute the SHA1 object id of the given C<FILENAME> and add the object to the 810object database. 811 812The function returns the SHA1 hash. 813 814=cut 815 816# TODO: Support for passing FILEHANDLE instead of FILENAME 817sub hash_and_insert_object { 818my($self,$filename) =@_; 819 820 carp "Bad filename\"$filename\""if$filename=~/[\r\n]/; 821 822$self->_open_hash_and_insert_object_if_needed(); 823my($in,$out) = ($self->{hash_object_in},$self->{hash_object_out}); 824 825unless(print$out $filename,"\n") { 826$self->_close_hash_and_insert_object(); 827 throw Error::Simple("out pipe went bad"); 828} 829 830chomp(my$hash= <$in>); 831unless(defined($hash)) { 832$self->_close_hash_and_insert_object(); 833 throw Error::Simple("in pipe went bad"); 834} 835 836return$hash; 837} 838 839sub _open_hash_and_insert_object_if_needed { 840my($self) =@_; 841 842return ifdefined($self->{hash_object_pid}); 843 844($self->{hash_object_pid},$self->{hash_object_in}, 845$self->{hash_object_out},$self->{hash_object_ctx}) = 846 command_bidi_pipe(qw(hash-object -w --stdin-paths --no-filters)); 847} 848 849sub _close_hash_and_insert_object { 850my($self) =@_; 851 852return unlessdefined($self->{hash_object_pid}); 853 854my@vars=map{'hash_object_'.$_}qw(pid in out ctx); 855 856 command_close_bidi_pipe(@$self{@vars}); 857delete@$self{@vars}; 858} 859 860=item cat_blob ( SHA1, FILEHANDLE ) 861 862Prints the contents of the blob identified by C<SHA1> to C<FILEHANDLE> and 863returns the number of bytes printed. 864 865=cut 866 867sub cat_blob { 868my($self,$sha1,$fh) =@_; 869 870$self->_open_cat_blob_if_needed(); 871my($in,$out) = ($self->{cat_blob_in},$self->{cat_blob_out}); 872 873unless(print$out $sha1,"\n") { 874$self->_close_cat_blob(); 875 throw Error::Simple("out pipe went bad"); 876} 877 878my$description= <$in>; 879if($description=~/ missing$/) { 880 carp "$sha1doesn't exist in the repository"; 881return-1; 882} 883 884if($description!~/^[0-9a-fA-F]{40} \S+ (\d+)$/) { 885 carp "Unexpected result returned from git cat-file"; 886return-1; 887} 888 889my$size=$1; 890 891my$blob; 892my$bytesRead=0; 893 894while(1) { 895my$bytesLeft=$size-$bytesRead; 896last unless$bytesLeft; 897 898my$bytesToRead=$bytesLeft<1024?$bytesLeft:1024; 899my$read=read($in,$blob,$bytesToRead,$bytesRead); 900unless(defined($read)) { 901$self->_close_cat_blob(); 902 throw Error::Simple("in pipe went bad"); 903} 904 905$bytesRead+=$read; 906} 907 908# Skip past the trailing newline. 909my$newline; 910my$read=read($in,$newline,1); 911unless(defined($read)) { 912$self->_close_cat_blob(); 913 throw Error::Simple("in pipe went bad"); 914} 915unless($read==1&&$newlineeq"\n") { 916$self->_close_cat_blob(); 917 throw Error::Simple("didn't find newline after blob"); 918} 919 920unless(print$fh $blob) { 921$self->_close_cat_blob(); 922 throw Error::Simple("couldn't write to passed in filehandle"); 923} 924 925return$size; 926} 927 928sub _open_cat_blob_if_needed { 929my($self) =@_; 930 931return ifdefined($self->{cat_blob_pid}); 932 933($self->{cat_blob_pid},$self->{cat_blob_in}, 934$self->{cat_blob_out},$self->{cat_blob_ctx}) = 935 command_bidi_pipe(qw(cat-file --batch)); 936} 937 938sub _close_cat_blob { 939my($self) =@_; 940 941return unlessdefined($self->{cat_blob_pid}); 942 943my@vars=map{'cat_blob_'.$_}qw(pid in out ctx); 944 945 command_close_bidi_pipe(@$self{@vars}); 946delete@$self{@vars}; 947} 948 949 950{# %TEMP_* Lexical Context 951 952my(%TEMP_FILEMAP,%TEMP_FILES); 953 954=item temp_acquire ( NAME ) 955 956Attempts to retreive the temporary file mapped to the string C<NAME>. If an 957associated temp file has not been created this session or was closed, it is 958created, cached, and set for autoflush and binmode. 959 960Internally locks the file mapped to C<NAME>. This lock must be released with 961C<temp_release()> when the temp file is no longer needed. Subsequent attempts 962to retrieve temporary files mapped to the same C<NAME> while still locked will 963cause an error. This locking mechanism provides a weak guarantee and is not 964threadsafe. It does provide some error checking to help prevent temp file refs 965writing over one another. 966 967In general, the L<File::Handle> returned should not be closed by consumers as 968it defeats the purpose of this caching mechanism. If you need to close the temp 969file handle, then you should use L<File::Temp> or another temp file faculty 970directly. If a handle is closed and then requested again, then a warning will 971issue. 972 973=cut 974 975sub temp_acquire { 976my$temp_fd= _temp_cache(@_); 977 978$TEMP_FILES{$temp_fd}{locked} =1; 979$temp_fd; 980} 981 982=item temp_release ( NAME ) 983 984=item temp_release ( FILEHANDLE ) 985 986Releases a lock acquired through C<temp_acquire()>. Can be called either with 987the C<NAME> mapping used when acquiring the temp file or with the C<FILEHANDLE> 988referencing a locked temp file. 989 990Warns if an attempt is made to release a file that is not locked. 991 992The temp file will be truncated before being released. This can help to reduce 993disk I/O where the system is smart enough to detect the truncation while data 994is in the output buffers. Beware that after the temp file is released and 995truncated, any operations on that file may fail miserably until it is 996re-acquired. All contents are lost between each release and acquire mapped to 997the same string. 998 999=cut10001001sub temp_release {1002my($self,$temp_fd,$trunc) = _maybe_self(@_);10031004if(exists$TEMP_FILEMAP{$temp_fd}) {1005$temp_fd=$TEMP_FILES{$temp_fd};1006}1007unless($TEMP_FILES{$temp_fd}{locked}) {1008 carp "Attempt to release temp file '",1009$temp_fd,"' that has not been locked";1010}1011 temp_reset($temp_fd)if$truncand$temp_fd->opened;10121013$TEMP_FILES{$temp_fd}{locked} =0;1014undef;1015}10161017sub _temp_cache {1018my($self,$name) = _maybe_self(@_);10191020 _verify_require();10211022my$temp_fd= \$TEMP_FILEMAP{$name};1023if(defined$$temp_fdand$$temp_fd->opened) {1024if($TEMP_FILES{$$temp_fd}{locked}) {1025 throw Error::Simple("Temp file with moniker '".1026$name."' already in use");1027}1028}else{1029if(defined$$temp_fd) {1030# then we're here because of a closed handle.1031 carp "Temp file '",$name,1032"' was closed. Opening replacement.";1033}1034my$fname;10351036my$tmpdir;1037if(defined$self) {1038$tmpdir=$self->repo_path();1039}10401041($$temp_fd,$fname) = File::Temp->tempfile(1042'Git_XXXXXX', UNLINK =>1, DIR =>$tmpdir,1043)or throw Error::Simple("couldn't open new temp file");10441045$$temp_fd->autoflush;1046binmode$$temp_fd;1047$TEMP_FILES{$$temp_fd}{fname} =$fname;1048}1049$$temp_fd;1050}10511052sub _verify_require {1053eval{require File::Temp;require File::Spec; };1054$@and throw Error::Simple($@);1055}10561057=item temp_reset ( FILEHANDLE )10581059Truncates and resets the position of the C<FILEHANDLE>.10601061=cut10621063sub temp_reset {1064my($self,$temp_fd) = _maybe_self(@_);10651066truncate$temp_fd,01067or throw Error::Simple("couldn't truncate file");1068sysseek($temp_fd,0, SEEK_SET)and seek($temp_fd,0, SEEK_SET)1069or throw Error::Simple("couldn't seek to beginning of file");1070sysseek($temp_fd,0, SEEK_CUR) ==0and tell($temp_fd) ==01071or throw Error::Simple("expected file position to be reset");1072}10731074=item temp_path ( NAME )10751076=item temp_path ( FILEHANDLE )10771078Returns the filename associated with the given tempfile.10791080=cut10811082sub temp_path {1083my($self,$temp_fd) = _maybe_self(@_);10841085if(exists$TEMP_FILEMAP{$temp_fd}) {1086$temp_fd=$TEMP_FILEMAP{$temp_fd};1087}1088$TEMP_FILES{$temp_fd}{fname};1089}10901091sub END{1092unlink values%TEMP_FILEMAPif%TEMP_FILEMAP;1093}10941095}# %TEMP_* Lexical Context10961097=back10981099=head1 ERROR HANDLING11001101All functions are supposed to throw Perl exceptions in case of errors.1102See the L<Error> module on how to catch those. Most exceptions are mere1103L<Error::Simple> instances.11041105However, the C<command()>, C<command_oneline()> and C<command_noisy()>1106functions suite can throw C<Git::Error::Command> exceptions as well: those are1107thrown when the external command returns an error code and contain the error1108code as well as access to the captured command's output. The exception class1109provides the usual C<stringify> and C<value> (command's exit code) methods and1110in addition also a C<cmd_output> method that returns either an array or a1111string with the captured command output (depending on the original function1112call context; C<command_noisy()> returns C<undef>) and $<cmdline> which1113returns the command and its arguments (but without proper quoting).11141115Note that the C<command_*_pipe()> functions cannot throw this exception since1116it has no idea whether the command failed or not. You will only find out1117at the time you C<close> the pipe; if you want to have that automated,1118use C<command_close_pipe()>, which can throw the exception.11191120=cut11211122{1123package Git::Error::Command;11241125@Git::Error::Command::ISA =qw(Error);11261127sub new {1128my$self=shift;1129my$cmdline=''.shift;1130my$value=0+shift;1131my$outputref=shift;1132my(@args) = ();11331134local$Error::Depth =$Error::Depth +1;11351136push(@args,'-cmdline',$cmdline);1137push(@args,'-value',$value);1138push(@args,'-outputref',$outputref);11391140$self->SUPER::new(-text =>'command returned error',@args);1141}11421143sub stringify {1144my$self=shift;1145my$text=$self->SUPER::stringify;1146$self->cmdline() .': '.$text.': '.$self->value() ."\n";1147}11481149sub cmdline {1150my$self=shift;1151$self->{'-cmdline'};1152}11531154sub cmd_output {1155my$self=shift;1156my$ref=$self->{'-outputref'};1157defined$refor undef;1158if(ref$refeq'ARRAY') {1159return@$ref;1160}else{# SCALAR1161return$$ref;1162}1163}1164}11651166=over 411671168=item git_cmd_try { CODE } ERRMSG11691170This magical statement will automatically catch any C<Git::Error::Command>1171exceptions thrown by C<CODE> and make your program die with C<ERRMSG>1172on its lips; the message will have %s substituted for the command line1173and %d for the exit status. This statement is useful mostly for producing1174more user-friendly error messages.11751176In case of no exception caught the statement returns C<CODE>'s return value.11771178Note that this is the only auto-exported function.11791180=cut11811182sub git_cmd_try(&$) {1183my($code,$errmsg) =@_;1184my@result;1185my$err;1186my$array=wantarray;1187try{1188if($array) {1189@result= &$code;1190}else{1191$result[0] = &$code;1192}1193} catch Git::Error::Command with {1194my$E=shift;1195$err=$errmsg;1196$err=~s/\%s/$E->cmdline()/ge;1197$err=~s/\%d/$E->value()/ge;1198# We can't croak here since Error.pm would mangle1199# that to Error::Simple.1200};1201$errand croak $err;1202return$array?@result:$result[0];1203}120412051206=back12071208=head1 COPYRIGHT12091210Copyright 2006 by Petr Baudis E<lt>pasky@suse.czE<gt>.12111212This module is free software; it may be used, copied, modified1213and distributed under the terms of the GNU General Public Licence,1214either version 2, or (at your option) any later version.12151216=cut121712181219# Take raw method argument list and return ($obj, @args) in case1220# the method was called upon an instance and (undef, @args) if1221# it was called directly.1222sub _maybe_self {1223 UNIVERSAL::isa($_[0],'Git') ?@_: (undef,@_);1224}12251226# Check if the command id is something reasonable.1227sub _check_valid_cmd {1228my($cmd) =@_;1229$cmd=~/^[a-z0-9A-Z_-]+$/or throw Error::Simple("bad command:$cmd");1230}12311232# Common backend for the pipe creators.1233sub _command_common_pipe {1234my$direction=shift;1235my($self,@p) = _maybe_self(@_);1236my(%opts,$cmd,@args);1237if(ref$p[0]) {1238($cmd,@args) = @{shift@p};1239%opts=ref$p[0] ? %{$p[0]} :@p;1240}else{1241($cmd,@args) =@p;1242}1243 _check_valid_cmd($cmd);12441245my$fh;1246if($^Oeq'MSWin32') {1247# ActiveState Perl1248#defined $opts{STDERR} and1249# warn 'ignoring STDERR option - running w/ ActiveState';1250$directioneq'-|'or1251die'input pipe for ActiveState not implemented';1252# the strange construction with *ACPIPE is just to1253# explain the tie below that we want to bind to1254# a handle class, not scalar. It is not known if1255# it is something specific to ActiveState Perl or1256# just a Perl quirk.1257 tie (*ACPIPE,'Git::activestate_pipe',$cmd,@args);1258$fh= *ACPIPE;12591260}else{1261my$pid=open($fh,$direction);1262if(not defined$pid) {1263 throw Error::Simple("open failed:$!");1264}elsif($pid==0) {1265if(defined$opts{STDERR}) {1266close STDERR;1267}1268if($opts{STDERR}) {1269open(STDERR,'>&',$opts{STDERR})1270or die"dup failed:$!";1271}1272 _cmd_exec($self,$cmd,@args);1273}1274}1275returnwantarray? ($fh,join(' ',$cmd,@args)) :$fh;1276}12771278# When already in the subprocess, set up the appropriate state1279# for the given repository and execute the git command.1280sub _cmd_exec {1281my($self,@args) =@_;1282if($self) {1283$self->repo_path()and$ENV{'GIT_DIR'} =$self->repo_path();1284$self->repo_path()and$self->wc_path()1285and$ENV{'GIT_WORK_TREE'} =$self->wc_path();1286$self->wc_path()and chdir($self->wc_path());1287$self->wc_subdir()and chdir($self->wc_subdir());1288}1289 _execv_git_cmd(@args);1290dieqq[exec "@args" failed:$!];1291}12921293# Execute the given Git command ($_[0]) with arguments ($_[1..])1294# by searching for it at proper places.1295sub _execv_git_cmd {exec('git',@_); }12961297# Close pipe to a subprocess.1298sub _cmd_close {1299my($fh,$ctx) =@_;1300if(not close$fh) {1301if($!) {1302# It's just close, no point in fatalities1303 carp "error closing pipe:$!";1304}elsif($?>>8) {1305# The caller should pepper this.1306 throw Git::Error::Command($ctx,$?>>8);1307}1308# else we might e.g. closed a live stream; the command1309# dying of SIGPIPE would drive us here.1310}1311}131213131314sub DESTROY {1315my($self) =@_;1316$self->_close_hash_and_insert_object();1317$self->_close_cat_blob();1318}131913201321# Pipe implementation for ActiveState Perl.13221323package Git::activestate_pipe;1324use strict;13251326sub TIEHANDLE {1327my($class,@params) =@_;1328# FIXME: This is probably horrible idea and the thing will explode1329# at the moment you give it arguments that require some quoting,1330# but I have no ActiveState clue... --pasky1331# Let's just hope ActiveState Perl does at least the quoting1332# correctly.1333my@data=qx{git@params};1334bless{ i =>0, data => \@data},$class;1335}13361337sub READLINE {1338my$self=shift;1339if($self->{i} >=scalar@{$self->{data}}) {1340returnundef;1341}1342my$i=$self->{i};1343if(wantarray) {1344$self->{i} =$#{$self->{'data'}} +1;1345returnsplice(@{$self->{'data'}},$i);1346}1347$self->{i} =$i+1;1348return$self->{'data'}->[$i];1349}13501351sub CLOSE {1352my$self=shift;1353delete$self->{data};1354delete$self->{i};1355}13561357sub EOF {1358my$self=shift;1359return($self->{i} >=scalar@{$self->{data}});1360}1361136213631;# Famous last words