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 prompt 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 cwd); 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($ctx,$fh); 271 272}elsif(not wantarray) { 273local$/; 274my$text= <$fh>; 275try{ 276 _cmd_close($ctx,$fh); 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($ctx,$fh); 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($ctx,$fh); 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($ctx,$fh); 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); 399my($self) = _maybe_self(@_); 400local%ENV=%ENV; 401my$cwd_save=undef; 402if($self) { 403shift; 404$cwd_save= cwd(); 405 _setup_git_cmd_env($self); 406} 407$pid= open2($in,$out,'git',@_); 408chdir($cwd_save)if$cwd_save; 409return($pid,$in,$out,join(' ',@_)); 410} 411 412=item command_close_bidi_pipe ( PID, PIPE_IN, PIPE_OUT [, CTX] ) 413 414Close the C<PIPE_IN> and C<PIPE_OUT> as returned from C<command_bidi_pipe()>, 415checking whether the command finished successfully. The optional C<CTX> 416argument is required if you want to see the command name in the error message, 417and it is the fourth value returned by C<command_bidi_pipe()>. The call idiom 418is: 419 420 my ($pid, $in, $out, $ctx) = $r->command_bidi_pipe('cat-file --batch-check'); 421 print $out "000000000\n"; 422 while (<$in>) { ... } 423 $r->command_close_bidi_pipe($pid, $in, $out, $ctx); 424 425Note that you should not rely on whatever actually is in C<CTX>; 426currently it is simply the command name but in future the context might 427have more complicated structure. 428 429C<PIPE_IN> and C<PIPE_OUT> may be C<undef> if they have been closed prior to 430calling this function. This may be useful in a query-response type of 431commands where caller first writes a query and later reads response, eg: 432 433 my ($pid, $in, $out, $ctx) = $r->command_bidi_pipe('cat-file --batch-check'); 434 print $out "000000000\n"; 435 close $out; 436 while (<$in>) { ... } 437 $r->command_close_bidi_pipe($pid, $in, undef, $ctx); 438 439This idiom may prevent potential dead locks caused by data sent to the output 440pipe not being flushed and thus not reaching the executed command. 441 442=cut 443 444sub command_close_bidi_pipe { 445local$?; 446my($self,$pid,$in,$out,$ctx) = _maybe_self(@_); 447 _cmd_close($ctx, (grep{defined} ($in,$out))); 448waitpid$pid,0; 449if($?>>8) { 450 throw Git::Error::Command($ctx,$?>>8); 451} 452} 453 454 455=item command_noisy ( COMMAND [, ARGUMENTS... ] ) 456 457Execute the given C<COMMAND> in the same way as command() does but do not 458capture the command output - the standard output is not redirected and goes 459to the standard output of the caller application. 460 461While the method is called command_noisy(), you might want to as well use 462it for the most silent Git commands which you know will never pollute your 463stdout but you want to avoid the overhead of the pipe setup when calling them. 464 465The function returns only after the command has finished running. 466 467=cut 468 469sub command_noisy { 470my($self,$cmd,@args) = _maybe_self(@_); 471 _check_valid_cmd($cmd); 472 473my$pid=fork; 474if(not defined$pid) { 475 throw Error::Simple("fork failed:$!"); 476}elsif($pid==0) { 477 _cmd_exec($self,$cmd,@args); 478} 479if(waitpid($pid,0) >0and$?>>8!=0) { 480 throw Git::Error::Command(join(' ',$cmd,@args),$?>>8); 481} 482} 483 484 485=item version () 486 487Return the Git version in use. 488 489=cut 490 491sub version { 492my$verstr= command_oneline('--version'); 493$verstr=~s/^git version //; 494$verstr; 495} 496 497 498=item exec_path () 499 500Return path to the Git sub-command executables (the same as 501C<git --exec-path>). Useful mostly only internally. 502 503=cut 504 505sub exec_path { command_oneline('--exec-path') } 506 507 508=item html_path () 509 510Return path to the Git html documentation (the same as 511C<git --html-path>). Useful mostly only internally. 512 513=cut 514 515sub html_path { command_oneline('--html-path') } 516 517=item prompt ( PROMPT , ISPASSWORD ) 518 519Query user C<PROMPT> and return answer from user. 520 521Honours GIT_ASKPASS and SSH_ASKPASS environment variables for querying 522the user. If no *_ASKPASS variable is set or an error occoured, 523the terminal is tried as a fallback. 524If C<ISPASSWORD> is set and true, the terminal disables echo. 525 526=cut 527 528sub prompt { 529my($prompt,$isPassword) =@_; 530my$ret; 531if(exists$ENV{'GIT_ASKPASS'}) { 532$ret= _prompt($ENV{'GIT_ASKPASS'},$prompt); 533} 534if(!defined$ret&&exists$ENV{'SSH_ASKPASS'}) { 535$ret= _prompt($ENV{'SSH_ASKPASS'},$prompt); 536} 537if(!defined$ret) { 538print STDERR $prompt; 539 STDERR->flush; 540if(defined$isPassword&&$isPassword) { 541require Term::ReadKey; 542 Term::ReadKey::ReadMode('noecho'); 543$ret=''; 544while(defined(my$key= Term::ReadKey::ReadKey(0))) { 545last if$key=~/[\012\015]/;# \n\r 546$ret.=$key; 547} 548 Term::ReadKey::ReadMode('restore'); 549print STDERR "\n"; 550 STDERR->flush; 551}else{ 552chomp($ret= <STDIN>); 553} 554} 555return$ret; 556} 557 558sub _prompt { 559my($askpass,$prompt) =@_; 560return unlesslength$askpass; 561$prompt=~s/\n/ /g; 562my$ret; 563open my$fh,"-|",$askpass,$promptorreturn; 564$ret= <$fh>; 565$ret=~s/[\015\012]//g;# strip \r\n, chomp does not work on all systems (i.e. windows) as expected 566close($fh); 567return$ret; 568} 569 570=item repo_path () 571 572Return path to the git repository. Must be called on a repository instance. 573 574=cut 575 576sub repo_path {$_[0]->{opts}->{Repository} } 577 578 579=item wc_path () 580 581Return path to the working copy. Must be called on a repository instance. 582 583=cut 584 585sub wc_path {$_[0]->{opts}->{WorkingCopy} } 586 587 588=item wc_subdir () 589 590Return path to the subdirectory inside of a working copy. Must be called 591on a repository instance. 592 593=cut 594 595sub wc_subdir {$_[0]->{opts}->{WorkingSubdir} ||=''} 596 597 598=item wc_chdir ( SUBDIR ) 599 600Change the working copy subdirectory to work within. The C<SUBDIR> is 601relative to the working copy root directory (not the current subdirectory). 602Must be called on a repository instance attached to a working copy 603and the directory must exist. 604 605=cut 606 607sub wc_chdir { 608my($self,$subdir) =@_; 609$self->wc_path() 610or throw Error::Simple("bare repository"); 611 612-d $self->wc_path().'/'.$subdir 613or throw Error::Simple("subdir not found:$subdir$!"); 614# Of course we will not "hold" the subdirectory so anyone 615# can delete it now and we will never know. But at least we tried. 616 617$self->{opts}->{WorkingSubdir} =$subdir; 618} 619 620 621=item config ( VARIABLE ) 622 623Retrieve the configuration C<VARIABLE> in the same manner as C<config> 624does. In scalar context requires the variable to be set only one time 625(exception is thrown otherwise), in array context returns allows the 626variable to be set multiple times and returns all the values. 627 628=cut 629 630sub config { 631return _config_common({},@_); 632} 633 634 635=item config_bool ( VARIABLE ) 636 637Retrieve the bool configuration C<VARIABLE>. The return value 638is usable as a boolean in perl (and C<undef> if it's not defined, 639of course). 640 641=cut 642 643sub config_bool { 644my$val=scalar _config_common({'kind'=>'--bool'},@_); 645 646# Do not rewrite this as return (defined $val && $val eq 'true') 647# as some callers do care what kind of falsehood they receive. 648if(!defined$val) { 649returnundef; 650}else{ 651return$valeq'true'; 652} 653} 654 655 656=item config_path ( VARIABLE ) 657 658Retrieve the path configuration C<VARIABLE>. The return value 659is an expanded path or C<undef> if it's not defined. 660 661=cut 662 663sub config_path { 664return _config_common({'kind'=>'--path'},@_); 665} 666 667 668=item config_int ( VARIABLE ) 669 670Retrieve the integer configuration C<VARIABLE>. The return value 671is simple decimal number. An optional value suffix of 'k', 'm', 672or 'g' in the config file will cause the value to be multiplied 673by 1024, 1048576 (1024^2), or 1073741824 (1024^3) prior to output. 674It would return C<undef> if configuration variable is not defined, 675 676=cut 677 678sub config_int { 679returnscalar _config_common({'kind'=>'--int'},@_); 680} 681 682# Common subroutine to implement bulk of what the config* family of methods 683# do. This curently wraps command('config') so it is not so fast. 684sub _config_common { 685my($opts) =shift@_; 686my($self,$var) = _maybe_self(@_); 687 688try{ 689my@cmd= ('config',$opts->{'kind'} ?$opts->{'kind'} : ()); 690unshift@cmd,$selfif$self; 691if(wantarray) { 692return command(@cmd,'--get-all',$var); 693}else{ 694return command_oneline(@cmd,'--get',$var); 695} 696} catch Git::Error::Command with { 697my$E=shift; 698if($E->value() ==1) { 699# Key not found. 700return; 701}else{ 702 throw $E; 703} 704}; 705} 706 707=item get_colorbool ( NAME ) 708 709Finds if color should be used for NAMEd operation from the configuration, 710and returns boolean (true for "use color", false for "do not use color"). 711 712=cut 713 714sub get_colorbool { 715my($self,$var) =@_; 716my$stdout_to_tty= (-t STDOUT) ?"true":"false"; 717my$use_color=$self->command_oneline('config','--get-colorbool', 718$var,$stdout_to_tty); 719return($use_coloreq'true'); 720} 721 722=item get_color ( SLOT, COLOR ) 723 724Finds color for SLOT from the configuration, while defaulting to COLOR, 725and returns the ANSI color escape sequence: 726 727 print $repo->get_color("color.interactive.prompt", "underline blue white"); 728 print "some text"; 729 print $repo->get_color("", "normal"); 730 731=cut 732 733sub get_color { 734my($self,$slot,$default) =@_; 735my$color=$self->command_oneline('config','--get-color',$slot,$default); 736if(!defined$color) { 737$color=""; 738} 739return$color; 740} 741 742=item remote_refs ( REPOSITORY [, GROUPS [, REFGLOBS ] ] ) 743 744This function returns a hashref of refs stored in a given remote repository. 745The hash is in the format C<refname =\> hash>. For tags, the C<refname> entry 746contains the tag object while a C<refname^{}> entry gives the tagged objects. 747 748C<REPOSITORY> has the same meaning as the appropriate C<git-ls-remote> 749argument; either a URL or a remote name (if called on a repository instance). 750C<GROUPS> is an optional arrayref that can contain 'tags' to return all the 751tags and/or 'heads' to return all the heads. C<REFGLOB> is an optional array 752of strings containing a shell-like glob to further limit the refs returned in 753the hash; the meaning is again the same as the appropriate C<git-ls-remote> 754argument. 755 756This function may or may not be called on a repository instance. In the former 757case, remote names as defined in the repository are recognized as repository 758specifiers. 759 760=cut 761 762sub remote_refs { 763my($self,$repo,$groups,$refglobs) = _maybe_self(@_); 764my@args; 765if(ref$groupseq'ARRAY') { 766foreach(@$groups) { 767if($_eq'heads') { 768push(@args,'--heads'); 769}elsif($_eq'tags') { 770push(@args,'--tags'); 771}else{ 772# Ignore unknown groups for future 773# compatibility 774} 775} 776} 777push(@args,$repo); 778if(ref$refglobseq'ARRAY') { 779push(@args,@$refglobs); 780} 781 782my@self=$self? ($self) : ();# Ultra trickery 783my($fh,$ctx) = Git::command_output_pipe(@self,'ls-remote',@args); 784my%refs; 785while(<$fh>) { 786chomp; 787my($hash,$ref) =split(/\t/,$_,2); 788$refs{$ref} =$hash; 789} 790 Git::command_close_pipe(@self,$fh,$ctx); 791return \%refs; 792} 793 794 795=item ident ( TYPE | IDENTSTR ) 796 797=item ident_person ( TYPE | IDENTSTR | IDENTARRAY ) 798 799This suite of functions retrieves and parses ident information, as stored 800in the commit and tag objects or produced by C<var GIT_type_IDENT> (thus 801C<TYPE> can be either I<author> or I<committer>; case is insignificant). 802 803The C<ident> method retrieves the ident information from C<git var> 804and either returns it as a scalar string or as an array with the fields parsed. 805Alternatively, it can take a prepared ident string (e.g. from the commit 806object) and just parse it. 807 808C<ident_person> returns the person part of the ident - name and email; 809it can take the same arguments as C<ident> or the array returned by C<ident>. 810 811The synopsis is like: 812 813 my ($name, $email, $time_tz) = ident('author'); 814 "$name <$email>" eq ident_person('author'); 815 "$name <$email>" eq ident_person($name); 816 $time_tz =~ /^\d+ [+-]\d{4}$/; 817 818=cut 819 820sub ident { 821my($self,$type) = _maybe_self(@_); 822my$identstr; 823if(lc$typeeq lc'committer'or lc$typeeq lc'author') { 824my@cmd= ('var','GIT_'.uc($type).'_IDENT'); 825unshift@cmd,$selfif$self; 826$identstr= command_oneline(@cmd); 827}else{ 828$identstr=$type; 829} 830if(wantarray) { 831return$identstr=~/^(.*) <(.*)> (\d+ [+-]\d{4})$/; 832}else{ 833return$identstr; 834} 835} 836 837sub ident_person { 838my($self,@ident) = _maybe_self(@_); 839$#ident==0and@ident=$self?$self->ident($ident[0]) : ident($ident[0]); 840return"$ident[0] <$ident[1]>"; 841} 842 843 844=item hash_object ( TYPE, FILENAME ) 845 846Compute the SHA1 object id of the given C<FILENAME> considering it is 847of the C<TYPE> object type (C<blob>, C<commit>, C<tree>). 848 849The method can be called without any instance or on a specified Git repository, 850it makes zero difference. 851 852The function returns the SHA1 hash. 853 854=cut 855 856# TODO: Support for passing FILEHANDLE instead of FILENAME 857sub hash_object { 858my($self,$type,$file) = _maybe_self(@_); 859 command_oneline('hash-object','-t',$type,$file); 860} 861 862 863=item hash_and_insert_object ( FILENAME ) 864 865Compute the SHA1 object id of the given C<FILENAME> and add the object to the 866object database. 867 868The function returns the SHA1 hash. 869 870=cut 871 872# TODO: Support for passing FILEHANDLE instead of FILENAME 873sub hash_and_insert_object { 874my($self,$filename) =@_; 875 876 carp "Bad filename\"$filename\""if$filename=~/[\r\n]/; 877 878$self->_open_hash_and_insert_object_if_needed(); 879my($in,$out) = ($self->{hash_object_in},$self->{hash_object_out}); 880 881unless(print$out $filename,"\n") { 882$self->_close_hash_and_insert_object(); 883 throw Error::Simple("out pipe went bad"); 884} 885 886chomp(my$hash= <$in>); 887unless(defined($hash)) { 888$self->_close_hash_and_insert_object(); 889 throw Error::Simple("in pipe went bad"); 890} 891 892return$hash; 893} 894 895sub _open_hash_and_insert_object_if_needed { 896my($self) =@_; 897 898return ifdefined($self->{hash_object_pid}); 899 900($self->{hash_object_pid},$self->{hash_object_in}, 901$self->{hash_object_out},$self->{hash_object_ctx}) = 902$self->command_bidi_pipe(qw(hash-object -w --stdin-paths --no-filters)); 903} 904 905sub _close_hash_and_insert_object { 906my($self) =@_; 907 908return unlessdefined($self->{hash_object_pid}); 909 910my@vars=map{'hash_object_'.$_}qw(pid in out ctx); 911 912 command_close_bidi_pipe(@$self{@vars}); 913delete@$self{@vars}; 914} 915 916=item cat_blob ( SHA1, FILEHANDLE ) 917 918Prints the contents of the blob identified by C<SHA1> to C<FILEHANDLE> and 919returns the number of bytes printed. 920 921=cut 922 923sub cat_blob { 924my($self,$sha1,$fh) =@_; 925 926$self->_open_cat_blob_if_needed(); 927my($in,$out) = ($self->{cat_blob_in},$self->{cat_blob_out}); 928 929unless(print$out $sha1,"\n") { 930$self->_close_cat_blob(); 931 throw Error::Simple("out pipe went bad"); 932} 933 934my$description= <$in>; 935if($description=~/ missing$/) { 936 carp "$sha1doesn't exist in the repository"; 937return-1; 938} 939 940if($description!~/^[0-9a-fA-F]{40} \S+ (\d+)$/) { 941 carp "Unexpected result returned from git cat-file"; 942return-1; 943} 944 945my$size=$1; 946 947my$blob; 948my$bytesRead=0; 949 950while(1) { 951my$bytesLeft=$size-$bytesRead; 952last unless$bytesLeft; 953 954my$bytesToRead=$bytesLeft<1024?$bytesLeft:1024; 955my$read=read($in,$blob,$bytesToRead,$bytesRead); 956unless(defined($read)) { 957$self->_close_cat_blob(); 958 throw Error::Simple("in pipe went bad"); 959} 960 961$bytesRead+=$read; 962} 963 964# Skip past the trailing newline. 965my$newline; 966my$read=read($in,$newline,1); 967unless(defined($read)) { 968$self->_close_cat_blob(); 969 throw Error::Simple("in pipe went bad"); 970} 971unless($read==1&&$newlineeq"\n") { 972$self->_close_cat_blob(); 973 throw Error::Simple("didn't find newline after blob"); 974} 975 976unless(print$fh $blob) { 977$self->_close_cat_blob(); 978 throw Error::Simple("couldn't write to passed in filehandle"); 979} 980 981return$size; 982} 983 984sub _open_cat_blob_if_needed { 985my($self) =@_; 986 987return ifdefined($self->{cat_blob_pid}); 988 989($self->{cat_blob_pid},$self->{cat_blob_in}, 990$self->{cat_blob_out},$self->{cat_blob_ctx}) = 991$self->command_bidi_pipe(qw(cat-file --batch)); 992} 993 994sub _close_cat_blob { 995my($self) =@_; 996 997return unlessdefined($self->{cat_blob_pid}); 998 999my@vars=map{'cat_blob_'.$_}qw(pid in out ctx);10001001 command_close_bidi_pipe(@$self{@vars});1002delete@$self{@vars};1003}100410051006{# %TEMP_* Lexical Context10071008my(%TEMP_FILEMAP,%TEMP_FILES);10091010=item temp_acquire ( NAME )10111012Attempts to retreive the temporary file mapped to the string C<NAME>. If an1013associated temp file has not been created this session or was closed, it is1014created, cached, and set for autoflush and binmode.10151016Internally locks the file mapped to C<NAME>. This lock must be released with1017C<temp_release()> when the temp file is no longer needed. Subsequent attempts1018to retrieve temporary files mapped to the same C<NAME> while still locked will1019cause an error. This locking mechanism provides a weak guarantee and is not1020threadsafe. It does provide some error checking to help prevent temp file refs1021writing over one another.10221023In general, the L<File::Handle> returned should not be closed by consumers as1024it defeats the purpose of this caching mechanism. If you need to close the temp1025file handle, then you should use L<File::Temp> or another temp file faculty1026directly. If a handle is closed and then requested again, then a warning will1027issue.10281029=cut10301031sub temp_acquire {1032my$temp_fd= _temp_cache(@_);10331034$TEMP_FILES{$temp_fd}{locked} =1;1035$temp_fd;1036}10371038=item temp_release ( NAME )10391040=item temp_release ( FILEHANDLE )10411042Releases a lock acquired through C<temp_acquire()>. Can be called either with1043the C<NAME> mapping used when acquiring the temp file or with the C<FILEHANDLE>1044referencing a locked temp file.10451046Warns if an attempt is made to release a file that is not locked.10471048The temp file will be truncated before being released. This can help to reduce1049disk I/O where the system is smart enough to detect the truncation while data1050is in the output buffers. Beware that after the temp file is released and1051truncated, any operations on that file may fail miserably until it is1052re-acquired. All contents are lost between each release and acquire mapped to1053the same string.10541055=cut10561057sub temp_release {1058my($self,$temp_fd,$trunc) = _maybe_self(@_);10591060if(exists$TEMP_FILEMAP{$temp_fd}) {1061$temp_fd=$TEMP_FILES{$temp_fd};1062}1063unless($TEMP_FILES{$temp_fd}{locked}) {1064 carp "Attempt to release temp file '",1065$temp_fd,"' that has not been locked";1066}1067 temp_reset($temp_fd)if$truncand$temp_fd->opened;10681069$TEMP_FILES{$temp_fd}{locked} =0;1070undef;1071}10721073sub _temp_cache {1074my($self,$name) = _maybe_self(@_);10751076 _verify_require();10771078my$temp_fd= \$TEMP_FILEMAP{$name};1079if(defined$$temp_fdand$$temp_fd->opened) {1080if($TEMP_FILES{$$temp_fd}{locked}) {1081 throw Error::Simple("Temp file with moniker '".1082$name."' already in use");1083}1084}else{1085if(defined$$temp_fd) {1086# then we're here because of a closed handle.1087 carp "Temp file '",$name,1088"' was closed. Opening replacement.";1089}1090my$fname;10911092my$tmpdir;1093if(defined$self) {1094$tmpdir=$self->repo_path();1095}10961097($$temp_fd,$fname) = File::Temp->tempfile(1098'Git_XXXXXX', UNLINK =>1, DIR =>$tmpdir,1099)or throw Error::Simple("couldn't open new temp file");11001101$$temp_fd->autoflush;1102binmode$$temp_fd;1103$TEMP_FILES{$$temp_fd}{fname} =$fname;1104}1105$$temp_fd;1106}11071108sub _verify_require {1109eval{require File::Temp;require File::Spec; };1110$@and throw Error::Simple($@);1111}11121113=item temp_reset ( FILEHANDLE )11141115Truncates and resets the position of the C<FILEHANDLE>.11161117=cut11181119sub temp_reset {1120my($self,$temp_fd) = _maybe_self(@_);11211122truncate$temp_fd,01123or throw Error::Simple("couldn't truncate file");1124sysseek($temp_fd,0, SEEK_SET)and seek($temp_fd,0, SEEK_SET)1125or throw Error::Simple("couldn't seek to beginning of file");1126sysseek($temp_fd,0, SEEK_CUR) ==0and tell($temp_fd) ==01127or throw Error::Simple("expected file position to be reset");1128}11291130=item temp_path ( NAME )11311132=item temp_path ( FILEHANDLE )11331134Returns the filename associated with the given tempfile.11351136=cut11371138sub temp_path {1139my($self,$temp_fd) = _maybe_self(@_);11401141if(exists$TEMP_FILEMAP{$temp_fd}) {1142$temp_fd=$TEMP_FILEMAP{$temp_fd};1143}1144$TEMP_FILES{$temp_fd}{fname};1145}11461147sub END{1148unlink values%TEMP_FILEMAPif%TEMP_FILEMAP;1149}11501151}# %TEMP_* Lexical Context11521153=back11541155=head1 ERROR HANDLING11561157All functions are supposed to throw Perl exceptions in case of errors.1158See the L<Error> module on how to catch those. Most exceptions are mere1159L<Error::Simple> instances.11601161However, the C<command()>, C<command_oneline()> and C<command_noisy()>1162functions suite can throw C<Git::Error::Command> exceptions as well: those are1163thrown when the external command returns an error code and contain the error1164code as well as access to the captured command's output. The exception class1165provides the usual C<stringify> and C<value> (command's exit code) methods and1166in addition also a C<cmd_output> method that returns either an array or a1167string with the captured command output (depending on the original function1168call context; C<command_noisy()> returns C<undef>) and $<cmdline> which1169returns the command and its arguments (but without proper quoting).11701171Note that the C<command_*_pipe()> functions cannot throw this exception since1172it has no idea whether the command failed or not. You will only find out1173at the time you C<close> the pipe; if you want to have that automated,1174use C<command_close_pipe()>, which can throw the exception.11751176=cut11771178{1179package Git::Error::Command;11801181@Git::Error::Command::ISA =qw(Error);11821183sub new {1184my$self=shift;1185my$cmdline=''.shift;1186my$value=0+shift;1187my$outputref=shift;1188my(@args) = ();11891190local$Error::Depth =$Error::Depth +1;11911192push(@args,'-cmdline',$cmdline);1193push(@args,'-value',$value);1194push(@args,'-outputref',$outputref);11951196$self->SUPER::new(-text =>'command returned error',@args);1197}11981199sub stringify {1200my$self=shift;1201my$text=$self->SUPER::stringify;1202$self->cmdline() .': '.$text.': '.$self->value() ."\n";1203}12041205sub cmdline {1206my$self=shift;1207$self->{'-cmdline'};1208}12091210sub cmd_output {1211my$self=shift;1212my$ref=$self->{'-outputref'};1213defined$refor undef;1214if(ref$refeq'ARRAY') {1215return@$ref;1216}else{# SCALAR1217return$$ref;1218}1219}1220}12211222=over 412231224=item git_cmd_try { CODE } ERRMSG12251226This magical statement will automatically catch any C<Git::Error::Command>1227exceptions thrown by C<CODE> and make your program die with C<ERRMSG>1228on its lips; the message will have %s substituted for the command line1229and %d for the exit status. This statement is useful mostly for producing1230more user-friendly error messages.12311232In case of no exception caught the statement returns C<CODE>'s return value.12331234Note that this is the only auto-exported function.12351236=cut12371238sub git_cmd_try(&$) {1239my($code,$errmsg) =@_;1240my@result;1241my$err;1242my$array=wantarray;1243try{1244if($array) {1245@result= &$code;1246}else{1247$result[0] = &$code;1248}1249} catch Git::Error::Command with {1250my$E=shift;1251$err=$errmsg;1252$err=~s/\%s/$E->cmdline()/ge;1253$err=~s/\%d/$E->value()/ge;1254# We can't croak here since Error.pm would mangle1255# that to Error::Simple.1256};1257$errand croak $err;1258return$array?@result:$result[0];1259}126012611262=back12631264=head1 COPYRIGHT12651266Copyright 2006 by Petr Baudis E<lt>pasky@suse.czE<gt>.12671268This module is free software; it may be used, copied, modified1269and distributed under the terms of the GNU General Public Licence,1270either version 2, or (at your option) any later version.12711272=cut127312741275# Take raw method argument list and return ($obj, @args) in case1276# the method was called upon an instance and (undef, @args) if1277# it was called directly.1278sub _maybe_self {1279 UNIVERSAL::isa($_[0],'Git') ?@_: (undef,@_);1280}12811282# Check if the command id is something reasonable.1283sub _check_valid_cmd {1284my($cmd) =@_;1285$cmd=~/^[a-z0-9A-Z_-]+$/or throw Error::Simple("bad command:$cmd");1286}12871288# Common backend for the pipe creators.1289sub _command_common_pipe {1290my$direction=shift;1291my($self,@p) = _maybe_self(@_);1292my(%opts,$cmd,@args);1293if(ref$p[0]) {1294($cmd,@args) = @{shift@p};1295%opts=ref$p[0] ? %{$p[0]} :@p;1296}else{1297($cmd,@args) =@p;1298}1299 _check_valid_cmd($cmd);13001301my$fh;1302if($^Oeq'MSWin32') {1303# ActiveState Perl1304#defined $opts{STDERR} and1305# warn 'ignoring STDERR option - running w/ ActiveState';1306$directioneq'-|'or1307die'input pipe for ActiveState not implemented';1308# the strange construction with *ACPIPE is just to1309# explain the tie below that we want to bind to1310# a handle class, not scalar. It is not known if1311# it is something specific to ActiveState Perl or1312# just a Perl quirk.1313 tie (*ACPIPE,'Git::activestate_pipe',$cmd,@args);1314$fh= *ACPIPE;13151316}else{1317my$pid=open($fh,$direction);1318if(not defined$pid) {1319 throw Error::Simple("open failed:$!");1320}elsif($pid==0) {1321if(defined$opts{STDERR}) {1322close STDERR;1323}1324if($opts{STDERR}) {1325open(STDERR,'>&',$opts{STDERR})1326or die"dup failed:$!";1327}1328 _cmd_exec($self,$cmd,@args);1329}1330}1331returnwantarray? ($fh,join(' ',$cmd,@args)) :$fh;1332}13331334# When already in the subprocess, set up the appropriate state1335# for the given repository and execute the git command.1336sub _cmd_exec {1337my($self,@args) =@_;1338 _setup_git_cmd_env($self);1339 _execv_git_cmd(@args);1340dieqq[exec "@args" failed:$!];1341}13421343# set up the appropriate state for git command1344sub _setup_git_cmd_env {1345my$self=shift;1346if($self) {1347$self->repo_path()and$ENV{'GIT_DIR'} =$self->repo_path();1348$self->repo_path()and$self->wc_path()1349and$ENV{'GIT_WORK_TREE'} =$self->wc_path();1350$self->wc_path()and chdir($self->wc_path());1351$self->wc_subdir()and chdir($self->wc_subdir());1352}1353}13541355# Execute the given Git command ($_[0]) with arguments ($_[1..])1356# by searching for it at proper places.1357sub _execv_git_cmd {exec('git',@_); }13581359# Close pipe to a subprocess.1360sub _cmd_close {1361my$ctx=shift@_;1362foreachmy$fh(@_) {1363if(close$fh) {1364# nop1365}elsif($!) {1366# It's just close, no point in fatalities1367 carp "error closing pipe:$!";1368}elsif($?>>8) {1369# The caller should pepper this.1370 throw Git::Error::Command($ctx,$?>>8);1371}1372# else we might e.g. closed a live stream; the command1373# dying of SIGPIPE would drive us here.1374}1375}137613771378sub DESTROY {1379my($self) =@_;1380$self->_close_hash_and_insert_object();1381$self->_close_cat_blob();1382}138313841385# Pipe implementation for ActiveState Perl.13861387package Git::activestate_pipe;1388use strict;13891390sub TIEHANDLE {1391my($class,@params) =@_;1392# FIXME: This is probably horrible idea and the thing will explode1393# at the moment you give it arguments that require some quoting,1394# but I have no ActiveState clue... --pasky1395# Let's just hope ActiveState Perl does at least the quoting1396# correctly.1397my@data=qx{git@params};1398bless{ i =>0, data => \@data},$class;1399}14001401sub READLINE {1402my$self=shift;1403if($self->{i} >=scalar@{$self->{data}}) {1404returnundef;1405}1406my$i=$self->{i};1407if(wantarray) {1408$self->{i} =$#{$self->{'data'}} +1;1409returnsplice(@{$self->{'data'}},$i);1410}1411$self->{i} =$i+1;1412return$self->{'data'}->[$i];1413}14141415sub CLOSE {1416my$self=shift;1417delete$self->{data};1418delete$self->{i};1419}14201421sub EOF {1422my$self=shift;1423return($self->{i} >=scalar@{$self->{data}});1424}1425142614271;# Famous last words